You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "eschutho (via GitHub)" <gi...@apache.org> on 2026/08/19 15:32:32 UTC
[PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
eschutho opened a new pull request, #43336:
URL: https://github.com/apache/superset/pull/43336
## SUMMARY
The dashboard Excel export success email (#41133) links to a pre-signed S3 URL that is only valid for as long as *both* its own `ExpiresIn` window and the credentials that signed it remain valid. Deployments whose S3 client authenticates 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 pre-signed URL long before `EXCEL_EXPORT_LINK_TTL_SECONDS` elapses, since the *credentials'* session — not just the URL's own `ExpiresIn` — bounds how long it actually works.
To keep that promise regardless of credential lifetime, the email now links to a small Superset redirect endpoint (`GET .../export_xlsx/download/<job_id>/`) instead of a raw S3 URL. The link's own lifetime is enforced independently via the `key_value` store's `expires_on`, and the actual pre-signed URL is generated fresh — with then-current credentials — at click time, valid only long enough to complete a single download. The redirect intentionally requires no login, matching a raw pre-signed URL's own access model: the unguessable job id is the credential, and the dashboard access check already ran once when the export was requested.
Reusing this 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 delivery channel — which excluded guest/embedded dashboard sessions (`GuestUser`) entirely. A new `GET .../export_xlsx/status/<job_id>/` polling endpoint lets the frontend discover completion without an email: the `DownloadMenuItems` component now polls after enqueueing and auto-downloads once ready, so an embedded/guest session (no email) gets a working export too. A regular logged-in session gets both the browser auto-download and, still, the email — the polling arrives before the email does in practice.
`export_xlsx` needs a CSRF exemption for this to work end-to-end: it's a POST route now reachable from embedded/guest sessions whose fetch calls carry no CSRF token, the same reason `chart/data` is already in `WTF_CSRF_EXEMPT_LIST`.
## BEFORE/AFTER
**Before:** the export email links directly to a pre-signed S3 URL that can silently stop working hours before its promised expiry on IRSA-style deployments, and `POST export_xlsx` 400s for any session without an email address (all embedded/guest dashboards).
**After:** the export email (and, for guest sessions, browser polling) links to a Superset redirect that re-signs the S3 URL at click time; guest/embedded sessions can request and receive an export.
## TESTING INSTRUCTIONS
- `pytest tests/integration_tests/dashboards/api_tests.py -k "download_xlsx or export_xlsx"` — 17 new/updated tests
- `pytest tests/unit_tests/tasks/test_export_dashboard_excel.py` — 47 tests
- `pytest tests/integration_tests/security_tests.py -k test_views_are_secured`
- `npx jest src/dashboard/components/menu/DownloadMenuItems/DownloadMenuItems.test.tsx` — 18 tests (3 new, covering ready/pending/error polling states)
- `ruff check` / `ruff format --check` / `oxlint` / `prettier --check` all clean on touched files
- `mypy` clean on touched files (pre-existing, unrelated repo-wide errors aside)
## ADDITIONAL INFORMATION
- [ ] Has associated issue
- [ ] Required feature flags
- [x] Changes UI
- [x] Includes DB migration - N/A, reuses the existing `key_value` table via a new `KeyValueResource.EXCEL_EXPORT_DOWNLOAD` enum member, no schema change
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Introduces new feature or API
- [ ] Removes existing feature or API
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5346865497
Heads up: removing the guest guard here exposes an `AttributeError` on `g.user.id` in `export_xlsx` (`GuestUser` has no `id` attribute), so embedded guests get a 500 `Fatal error` instead of an export. Reproduced on a staging deployment carrying this branch's changes.
I opened #43340 against this branch with the fix (guest token passed to the task, guest user reconstructed via `get_guest_user_from_token` so RLS claims hold in the worker, shared lock slot 0 for guests) plus a unit test, so it can be merged into this PR before this lands on master.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43336:
URL: https://github.com/apache/superset/pull/43336#discussion_r3814455599
##########
superset/config.py:
##########
@@ -368,6 +368,7 @@ def _try_json_readsha(filepath: str, length: int) -> str | None:
WTF_CSRF_EXEMPT_LIST = [
"superset.charts.data.api.data",
"superset.dashboards.api.cache_dashboard_screenshot",
+ "superset.dashboards.api.export_xlsx",
Review Comment:
**Suggestion:** Exempting the authenticated `POST` export endpoint from CSRF protection allows a cross-site request to enqueue an export using a victim's Superset session whenever cookies are sent cross-site, such as deployments configured with `SESSION_COOKIE_SAMESITE="None"`. Keep CSRF validation for cookie-authenticated requests and use a narrowly scoped guest/embedded authentication mechanism instead of globally exempting this endpoint. [security]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Cross-site origins can trigger authenticated dashboard exports.
- ⚠️ Victim email and worker resources may be consumed.
- ⚠️ CSRF protection is bypassed for a state-changing endpoint.
```
</details>
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/config.py
**Line:** 371:371
**Comment:**
*Security: Exempting the authenticated `POST` export endpoint from CSRF protection allows a cross-site request to enqueue an export using a victim's Superset session whenever cookies are sent cross-site, such as deployments configured with `SESSION_COOKIE_SAMESITE="None"`. Keep CSRF validation for cookie-authenticated requests and use a narrowly scoped guest/embedded authentication mechanism instead of globally exempting this endpoint.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=f0d2ab67d4d4345e68d44bf04e0e1f0537542aed5af0a9f2d2988c8876ed6a98&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=f0d2ab67d4d4345e68d44bf04e0e1f0537542aed5af0a9f2d2988c8876ed6a98&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx:
##########
@@ -141,49 +154,103 @@ export const useDownloadMenuItems = (
fileName = parsed.parameters.filename;
}
} catch (error) {
- logging.warn('Failed to parse Content-Disposition header:', error);
+ logging.warn("Failed to parse Content-Disposition header:", error);
}
}
// Convert response to blob and trigger download
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
try {
- const a = document.createElement('a');
+ const a = document.createElement("a");
a.href = url;
a.download = fileName;
- a.style.display = 'none';
+ a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} finally {
window.URL.revokeObjectURL(url);
}
- addSuccessToast(t('Dashboard exported as example successfully'));
+ addSuccessToast(t("Dashboard exported as example successfully"));
} catch (error) {
logging.error(error);
- addDangerToast(t('Sorry, something went wrong. Try again later.'));
+ addDangerToast(t("Sorry, something went wrong. Try again later."));
}
};
- const onExportXlsx = async (mode: 'data' | 'images') => {
+ const pollExportStatus = (jobId: string, startedAt: number) => {
+ SupersetClient.get({
+ endpoint: `/api/v1/dashboard/export_xlsx/status/${jobId}/`,
+ })
+ .then(({ json }) => {
+ const {
+ status,
+ download_url: downloadUrl,
+ message,
+ } = json as ExportStatusResponse;
+ if (status === "ready") {
+ if (downloadUrl) {
+ window.location.href = downloadUrl;
+ }
+ addSuccessToast(t("Your export is ready and downloading."));
+ return;
+ }
+ if (status === "error") {
+ addDangerToast(
+ message || t("Sorry, something went wrong. Try again later."),
+ );
+ return;
+ }
+ if (Date.now() - startedAt > EXPORT_STATUS_POLL_TIMEOUT_MS) {
+ addDangerToast(
+ t("Your export is taking longer than expected. Try again later."),
+ );
+ return;
+ }
+ setTimeout(
+ () => pollExportStatus(jobId, startedAt),
+ EXPORT_STATUS_POLL_INTERVAL_MS,
+ );
Review Comment:
**Suggestion:** The polling timers are not retained or cancelled when the hook unmounts or the user navigates away. A pending export can therefore continue issuing status requests for up to five minutes, and a late successful response can display a toast or navigate the browser to the download URL after the originating dashboard has been destroyed. Track the timer and cancel it during cleanup, and ignore responses after unmount. [missing cleanup]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Dashboard navigation leaves polling requests running.
- ⚠️ Late completion can navigate the current page unexpectedly.
- ⚠️ Stale callbacks can display export toasts after teardown.
```
</details>
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
**Line:** 212:215
**Comment:**
*Missing Cleanup: The polling timers are not retained or cancelled when the hook unmounts or the user navigates away. A pending export can therefore continue issuing status requests for up to five minutes, and a late successful response can display a toast or navigate the browser to the download URL after the originating dashboard has been destroyed. Track the timer and cancel it during cleanup, and ignore responses after unmount.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=9f3080320a5a7ad6c45440f8d8f6dc40e01fe9ed6377e303f0db3a52870e2f6a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=9f3080320a5a7ad6c45440f8d8f6dc40e01fe9ed6377e303f0db3a52870e2f6a&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx:
##########
@@ -141,49 +154,103 @@ export const useDownloadMenuItems = (
fileName = parsed.parameters.filename;
}
} catch (error) {
- logging.warn('Failed to parse Content-Disposition header:', error);
+ logging.warn("Failed to parse Content-Disposition header:", error);
}
}
// Convert response to blob and trigger download
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
try {
- const a = document.createElement('a');
+ const a = document.createElement("a");
a.href = url;
a.download = fileName;
- a.style.display = 'none';
+ a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} finally {
window.URL.revokeObjectURL(url);
}
- addSuccessToast(t('Dashboard exported as example successfully'));
+ addSuccessToast(t("Dashboard exported as example successfully"));
} catch (error) {
logging.error(error);
- addDangerToast(t('Sorry, something went wrong. Try again later.'));
+ addDangerToast(t("Sorry, something went wrong. Try again later."));
}
};
- const onExportXlsx = async (mode: 'data' | 'images') => {
+ const pollExportStatus = (jobId: string, startedAt: number) => {
+ SupersetClient.get({
+ endpoint: `/api/v1/dashboard/export_xlsx/status/${jobId}/`,
+ })
+ .then(({ json }) => {
+ const {
+ status,
+ download_url: downloadUrl,
+ message,
+ } = json as ExportStatusResponse;
+ if (status === "ready") {
+ if (downloadUrl) {
+ window.location.href = downloadUrl;
+ }
+ addSuccessToast(t("Your export is ready and downloading."));
+ return;
+ }
+ if (status === "error") {
+ addDangerToast(
+ message || t("Sorry, something went wrong. Try again later."),
+ );
+ return;
+ }
+ if (Date.now() - startedAt > EXPORT_STATUS_POLL_TIMEOUT_MS) {
+ addDangerToast(
+ t("Your export is taking longer than expected. Try again later."),
+ );
+ return;
+ }
+ setTimeout(
+ () => pollExportStatus(jobId, startedAt),
+ EXPORT_STATUS_POLL_INTERVAL_MS,
+ );
+ })
+ .catch((error) => {
+ // A transient polling failure shouldn't give up the wait -- the export
+ // itself may still succeed -- so keep polling until the timeout.
+ logging.error(error);
+ if (Date.now() - startedAt > EXPORT_STATUS_POLL_TIMEOUT_MS) {
+ addDangerToast(t("Sorry, something went wrong. Try again later."));
+ return;
+ }
+ setTimeout(
+ () => pollExportStatus(jobId, startedAt),
+ EXPORT_STATUS_POLL_INTERVAL_MS,
+ );
+ });
+ };
+
+ const onExportXlsx = async (mode: "data" | "images") => {
try {
const { json } = await SupersetClient.post({
endpoint: `/api/v1/dashboard/${dashboardId}/export_xlsx/`,
jsonPayload: { active_data_mask: buildActiveDataMask(), mode },
});
// The throttle response (an export is already running) returns 202 with a
// message but no job_id; only a freshly enqueued job carries a job_id.
- if ((json as { job_id?: string })?.job_id) {
+ const jobId = (json as { job_id?: string })?.job_id;
+ if (jobId) {
addSuccessToast(
t(
"Your export is being prepared. You'll receive an email when it's ready.",
),
);
Review Comment:
**Suggestion:** The pending message explicitly promises that the user will receive an email, but the newly supported guest and embedded sessions have no email address and rely exclusively on polling and automatic download. This gives those users an incorrect delivery expectation; use wording that reflects the automatic download or select the message based on the session's notification capability. [logic error]
<details>
<summary><b>Severity Level:</b> Minor 🧹</summary>
```mdx
- ⚠️ Guest users receive an impossible email notification promise.
- ⚠️ Embedded users may wait for an email that never arrives.
- ✅ Polling still enables automatic download completion.
```
</details>
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx
**Line:** 242:246
**Comment:**
*Logic Error: The pending message explicitly promises that the user will receive an email, but the newly supported guest and embedded sessions have no email address and rely exclusively on polling and automatic download. This gives those users an incorrect delivery expectation; use wording that reflects the automatic download or select the message based on the session's notification capability.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=7d60d2cb08ce969ea52acb982f729328ac236e2d13a96e79a10205450f2b78de&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43336&comment_hash=7d60d2cb08ce969ea52acb982f729328ac236e2d13a96e79a10205450f2b78de&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5344386328
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 26fabcf77d5a7ef299c95f7442cfb1518eb9e772 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a85cc908a8fd000083cb0ec |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-43336--superset-docs-preview.netlify.app](https://deploy-preview-43336--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#FYtBCsMgEAD_sucuEaTF9Ad9hq6bRGJVXAuG0L_HzGkOMyeUmr-lwRvgAa7aRNvwJfSJO3FE7iXXhuuPpaGwSMhJ0CaPojGGtN9FqMe4PZeYj48f_8uaJ9GsjDWLVwOjySkm-F8) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-43336--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43336:
URL: https://github.com/apache/superset/pull/43336#discussion_r3817419744
##########
superset/dashboards/api.py:
##########
@@ -1787,12 +1803,9 @@ def export_xlsx(self, pk: int) -> WerkzeugResponse:
except SupersetSecurityException:
return self.response_403()
Review Comment:
Embedded guest requests now reach this path, but `GuestUser` has no persisted numeric `id`; building the lock key (and later enqueueing the task) raises before a job can be returned. Could this keep guest context separate from the user-id task contract, or continue rejecting guests until the worker can safely reconstruct that context?
##########
superset/dashboards/excel_export/download_link.py:
##########
@@ -0,0 +1,139 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Status tracking and long-lived download links for dashboard Excel exports.
+
+A raw S3 pre-signed URL is only valid for as long as *both* its own
+``ExpiresIn`` window and the credentials that signed it remain valid.
+Deployments whose S3 client authenticates via short-lived, auto-refreshed
+credentials (e.g. an EKS IRSA role assumed through
+``AssumeRoleWithWebIdentity``, which AWS caps at 12 hours and many clusters
+default to far less) can silently invalidate a pre-signed URL long before the
+``EXCEL_EXPORT_LINK_TTL_SECONDS`` window promised in the export email elapses,
+since the *credentials'* session -- not just the URL's own ``ExpiresIn`` --
+bounds how long it actually works.
+
+To keep that promise regardless of credential lifetime, the email links to a
+small Superset redirect endpoint instead of a raw S3 URL. The link's own
+lifetime is enforced by this module via the ``key_value`` store's
+``expires_on`` (independent of any credential session), and the actual
+pre-signed URL is generated fresh -- with then-current credentials -- at click
+time, valid only long enough to complete a single download.
+
+The redirect endpoint (``download_xlsx``) intentionally requires no login: a
+pre-signed S3 URL never did either, and the access-control decision for the
+underlying dashboard was already enforced once, when the export was
+originally requested (see ``security_manager.raise_for_access`` in
+``superset.dashboards.api.export_xlsx``). The unguessable key emailed only to
+that requester's own address is the same "possession of the link is the
+credential" model the raw pre-signed URL had; this module just re-signs it
+closer to when it is actually used.
+
+Every entry is keyed by ``job_id`` -- the same id the ``export_xlsx`` POST
+response hands back -- rather than a separately-generated identifier, so a
+caller that only has the job id (e.g. a polling frontend for a session with
+no email on file, such as an embedded/guest dashboard) can resolve both
+status and, once ready, a download link from that one id.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from superset.daos.key_value import KeyValueDAO
+from superset.key_value.types import JsonKeyValueCodec, KeyValueResource
+from superset.utils.urls import headless_url
+
+RESOURCE = KeyValueResource.EXCEL_EXPORT_DOWNLOAD
+CODEC = JsonKeyValueCodec()
+
+# The fresh pre-signed URL generated at click time only needs to outlive the
+# redirect and the browser/S3 handshake that follows it, not the link's own
+# multi-hour lifetime.
+PRESIGNED_URL_TTL_SECONDS = 300
+
+DOWNLOAD_PATH = "/api/v1/dashboard/export_xlsx/download/{job_id}/"
+
+STATUS_READY = "ready"
+STATUS_ERROR = "error"
+
+
+def _sweep_and_upsert(
+ job_id: UUID, value: dict[str, Any], expires_at: datetime
+) -> None:
+ # Lazily sweep expired entries each time one is written; there is no
+ # dedicated cleanup job, so this resource keeps itself tidy on write.
+ # upsert (not create) so a retried/duplicate write for the same job_id
+ # overwrites cleanly instead of colliding on the primary key.
+ KeyValueDAO.delete_expired_entries(RESOURCE)
+ KeyValueDAO.upsert_entry(
Review Comment:
The ready/error status is only staged in the SQLAlchemy session here. With a Redis distributed lock, releasing the lock does not commit that session, so Celery teardown rolls the entry back: polling remains pending and the emailed redirect returns 410. Could this write be committed transactionally before reporting the export ready?
##########
superset/dashboards/excel_export/download_link.py:
##########
@@ -0,0 +1,139 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Status tracking and long-lived download links for dashboard Excel exports.
+
+A raw S3 pre-signed URL is only valid for as long as *both* its own
+``ExpiresIn`` window and the credentials that signed it remain valid.
+Deployments whose S3 client authenticates via short-lived, auto-refreshed
+credentials (e.g. an EKS IRSA role assumed through
+``AssumeRoleWithWebIdentity``, which AWS caps at 12 hours and many clusters
+default to far less) can silently invalidate a pre-signed URL long before the
+``EXCEL_EXPORT_LINK_TTL_SECONDS`` window promised in the export email elapses,
+since the *credentials'* session -- not just the URL's own ``ExpiresIn`` --
+bounds how long it actually works.
+
+To keep that promise regardless of credential lifetime, the email links to a
+small Superset redirect endpoint instead of a raw S3 URL. The link's own
+lifetime is enforced by this module via the ``key_value`` store's
+``expires_on`` (independent of any credential session), and the actual
+pre-signed URL is generated fresh -- with then-current credentials -- at click
+time, valid only long enough to complete a single download.
+
+The redirect endpoint (``download_xlsx``) intentionally requires no login: a
+pre-signed S3 URL never did either, and the access-control decision for the
+underlying dashboard was already enforced once, when the export was
+originally requested (see ``security_manager.raise_for_access`` in
+``superset.dashboards.api.export_xlsx``). The unguessable key emailed only to
+that requester's own address is the same "possession of the link is the
+credential" model the raw pre-signed URL had; this module just re-signs it
+closer to when it is actually used.
+
+Every entry is keyed by ``job_id`` -- the same id the ``export_xlsx`` POST
+response hands back -- rather than a separately-generated identifier, so a
+caller that only has the job id (e.g. a polling frontend for a session with
+no email on file, such as an embedded/guest dashboard) can resolve both
+status and, once ready, a download link from that one id.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from superset.daos.key_value import KeyValueDAO
+from superset.key_value.types import JsonKeyValueCodec, KeyValueResource
+from superset.utils.urls import headless_url
+
+RESOURCE = KeyValueResource.EXCEL_EXPORT_DOWNLOAD
+CODEC = JsonKeyValueCodec()
+
+# The fresh pre-signed URL generated at click time only needs to outlive the
+# redirect and the browser/S3 handshake that follows it, not the link's own
+# multi-hour lifetime.
+PRESIGNED_URL_TTL_SECONDS = 300
+
+DOWNLOAD_PATH = "/api/v1/dashboard/export_xlsx/download/{job_id}/"
+
+STATUS_READY = "ready"
+STATUS_ERROR = "error"
+
+
+def _sweep_and_upsert(
+ job_id: UUID, value: dict[str, Any], expires_at: datetime
+) -> None:
+ # Lazily sweep expired entries each time one is written; there is no
+ # dedicated cleanup job, so this resource keeps itself tidy on write.
+ # upsert (not create) so a retried/duplicate write for the same job_id
+ # overwrites cleanly instead of colliding on the primary key.
+ KeyValueDAO.delete_expired_entries(RESOURCE)
+ KeyValueDAO.upsert_entry(
+ resource=RESOURCE,
+ value=value,
+ codec=CODEC,
+ key=job_id,
+ expires_on=expires_at,
+ )
+
+
+def build_download_url(job_id: UUID) -> str:
+ """The browser-facing URL that redirects to a freshly pre-signed S3 URL
+ for ``job_id``, once its export is ready."""
+ return headless_url(DOWNLOAD_PATH.format(job_id=job_id), user_friendly=True)
Review Comment:
`headless_url` joins this absolute path to the host and bypasses `APPLICATION_ROOT`. Deployments mounted below a prefix therefore email a root-level download URL that does not route to Superset. Could this use the prefix-aware URL helper (or otherwise include the application root)?
##########
superset/tasks/export_dashboard_excel.py:
##########
@@ -471,11 +498,14 @@ def export_dashboard_excel(
f"{current_app.config['EXCEL_EXPORT_S3_KEY_PREFIX']}"
f"{dashboard_id}/{job_id}.xlsx"
)
- ttl = current_app.config["EXCEL_EXPORT_LINK_TTL_SECONDS"]
s3.upload_file_to_s3(tmp_path, bucket, key)
- download_url = s3.generate_presigned_url(bucket, key, ttl)
expires_at = datetime.now(tz=timezone.utc) + timedelta(seconds=ttl)
+ # KeyValueEntry.expires_on comparisons use naive datetime.now(), so
+ # the stored expiry must be naive UTC too, not tz-aware.
+ download_url = create_download_link(
+ uuid.UUID(job_id), bucket, key, expires_at.replace(tzinfo=None)
Review Comment:
This stores a naive UTC timestamp, while `KeyValueEntry.is_expired()` compares it with naive local `datetime.now()`. On non-UTC servers the configured link lifetime is shifted by the timezone offset, so links can expire early or stay valid too long. Could the stored value and expiry comparison use the same timezone convention?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5515378287
Closing as superseded by #43805 per Elizabeth's handoff.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5515342800
@eschutho following your handoff: #43805 consolidates this branch plus the #43340 review rounds onto current master as one PR (your commits keep your authorship; the conflict here was against this branch's older state and resolves in the consolidation). Feel free to close this one as superseded, and any review is welcome over there.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz closed pull request #43336: fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions
URL: https://github.com/apache/superset/pull/43336
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5344435095
<!-- Bito Reply -->
The security concern regarding CSRF protection for the export endpoint is valid. Exempting state-changing endpoints from CSRF protection can indeed expose users to cross-site request forgery attacks, especially in configurations where cookies are sent cross-site. To resolve this, you should remove the global exemption for the endpoint and implement a more secure authentication mechanism, such as a guest token or a signed request parameter, for embedded or guest scenarios. Since the file `superset/config.py` is not present in the provided PR diff, I cannot implement the fix directly. Please locate the CSRF exemption configuration in `superset/config.py` and replace the global exemption with a more granular approach.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): decouple Excel export link lifetime from S3 credential expiry, and support guest/embedded sessions [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43336:
URL: https://github.com/apache/superset/pull/43336#issuecomment-5344354193
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org