Skip to content

fix(csrf): recover from an expired CSRF token without a page reload - #43655

Merged
rusackas merged 4 commits into
apache:masterfrom
saurabhdamle11:fix/csrf-token
Sep 22, 2026
Merged

rusackas merged 4 commits into
apache:masterfrom
saurabhdamle11:fix/csrf-token

Conversation

@saurabhdamle11

Copy link
Copy Markdown
Contributor

SUMMARY

Fixes #43550.

When a cached CSRF token expired, JSON API mutations failed with an HTTP 400
GENERIC_BACKEND_ERROR (issue code 1011). SupersetClient handled HTTP 401 but
not CSRF-related 400s, so it neither refreshed the token nor retried the request.
The user saw a generic error and had to reload the page before the action (e.g.
saving a dataset) would succeed.

This change lets Superset recover from an expired CSRF token in JSON requests
without a page reload:

  • views/error_handling.py now returns a dedicated, machine-readable
    CSRF_ERROR type for JSON requests instead of a generic backend error. The
    existing non-JSON login redirect (from feat: redirect to /login when CSRF expired #14675) is unchanged. CSRF_ERROR is
    added to errors.py and to SAFE_ERROR_TYPES in error_sanitization.py so
    the type survives guest-user sanitization.
  • SupersetClientClass detects that error type, fetches a fresh token from
    /api/v1/security/csrf_token/, and retries the original request once.
  • A shared refresh promise ensures that when several requests fail
    concurrently, only one token refresh is issued rather than one per request.
    Retry is capped at a single attempt, so a request that fails again cannot
    trigger a refresh/retry loop.
  • Added a CsrfErrorMessage component, registered in setupErrorMessages, for
    the case where recovery is not possible — the replay was rejected too, most
    often because the session itself is gone.

Why a new CSRF_ERROR rather than the existing FRONTEND_CSRF_ERROR:
FRONTEND_CSRF_ERROR is a client-originated marker and is never emitted by the
backend. This is a server-emitted rejection from Flask-WTF, so it needs its own
type; reusing the frontend one would conflate two different origins.

Security note: this does not bypass or weaken CSRF validation. The refresh
only runs after Flask-WTF has already rejected the request, and only when the
server explicitly identifies the failure as CSRF_ERROR. The new token is
issued against the existing authenticated session, the refresh runs in the
same-origin application context (a cross-site attacker cannot execute it or read
the response), and the single-retry cap means a genuinely forged request fails
after one replay rather than looping.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A. The recovery is transparent; the visible change is the absence of an
error. The one new visual surface is CsrfErrorMessage, shown only when the
token refresh itself fails.

TESTING INSTRUCTIONS

  1. Set a short CSRF lifetime in superset_config.py:
    WTF_CSRF_TIME_LIMIT = 5
  2. Restart Superset, log in, and open the dataset editor.
  3. Wait longer than 5 seconds, then modify and save the dataset.
  4. Confirm the save succeeds without a page reload. In the Network tab, verify a
    request to /api/v1/security/csrf_token/ is issued and the original save
    request is retried once and succeeds.
  5. Trigger several mutations concurrently after expiry and confirm only one
    token refresh request is issued.
  6. Confirm non-JSON requests still redirect to login on CSRF expiry (unchanged).
  7. Run the added tests:
    pytest tests/unit_tests/views/test_error_handling.py

cd superset-frontend
npm run test -- packages/superset-ui-core/test/connection/SupersetClientCsrfRecovery.test.ts
npm run test -- src/components/ErrorMessage/CsrfErrorMessage.test.tsx

ADDITIONAL INFORMATION

  • Has associated issue: Expired CSRF token causes JSON API mutations to fail without recovery #43550
  • Required feature flags:
  • 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

Note for reviewers: this adds a public refreshCSRFToken() method on
SupersetClientClass and a new CSRF_ERROR member to the exported
SupersetApiErrorType / ErrorTypeEnum in @superset-ui/core. Both are
additive and backwards-compatible, but they are consumable surface for plugins.

@dosubot dosubot Bot added authentication Related to authentication change:backend Requires changing the backend change:frontend Requires changing the frontend labels Aug 28, 2026
@bito-code-review

bito-code-review Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #80ef48

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx - 1
    • Unused default export · Line 51-51
      This `export default` is unused and inconsistent with the sibling error components: `FrontendNetworkErrorMessage`, `DatabaseErrorMessage`, `TimeoutErrorMessage`, etc. all use named exports only, and `index.tsx`/`setupErrorMessages.ts` import the named `CsrfErrorMessage`. Consider removing the default export to avoid dead code and divergent conventions.
Review Details
  • Files reviewed - 13 · Commit Range: 3562966..3562966
    • superset-frontend/packages/superset-ui-core/src/connection/SupersetClientClass.ts
    • superset-frontend/packages/superset-ui-core/src/connection/constants.ts
    • superset-frontend/packages/superset-ui-core/src/query/api/v1/types.ts
    • superset-frontend/packages/superset-ui-core/src/query/types/Query.ts
    • superset-frontend/packages/superset-ui-core/test/connection/SupersetClientCsrfRecovery.test.ts
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.test.tsx
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx
    • superset-frontend/src/components/ErrorMessage/index.tsx
    • superset-frontend/src/setup/setupErrorMessages.ts
    • superset/errors.py
    • superset/utils/error_sanitization.py
    • superset/views/error_handling.py
    • tests/unit_tests/views/test_error_handling.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
    • Eslint (Linter) - ✔︎ 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

AI Code Review powered by Bito Logo

@codecov

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.13%. Comparing base (f69023a) to head (9c0a5f0).
⚠️ Report is 118 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43655      +/-   ##
==========================================
- Coverage   80.14%   80.13%   -0.01%     
==========================================
  Files        2923     2924       +1     
  Lines      172121   172253     +132     
  Branches    39952    39986      +34     
==========================================
+ Hits       137945   138041      +96     
- Misses      31599    31625      +26     
- Partials     2577     2587      +10     
Flag Coverage Δ
hive 37.36% <50.00%> (-0.03%) ⬇️
javascript 75.67% <100.00%> (+<0.01%) ⬆️
mysql 56.92% <50.00%> (-0.06%) ⬇️
postgres 56.94% <50.00%> (-0.06%) ⬇️
presto 39.25% <50.00%> (-0.04%) ⬇️
python 84.49% <100.00%> (-0.03%) ⬇️
sqlite 56.64% <50.00%> (-0.06%) ⬇️
unit 75.79% <100.00%> (-0.01%) ⬇️

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.

@saurabhdamle11 saurabhdamle11 changed the title csrf error fix fix(csrf): recover from an expired CSRF token without a page reload Aug 28, 2026
@rusackas
rusackas requested review from eschutho and msyavuz August 29, 2026 03:22
@bito-code-review

bito-code-review Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #81ca4f

Actionable Suggestions - 0
Additional Suggestions - 4
  • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx - 1
    • Unused default export · Line 51-51
      `export default CsrfErrorMessage` is never imported anywhere. Consumers use the named export via `index.tsx` (`export { CsrfErrorMessage }`) and the test imports the named export. No sibling ErrorMessage component uses a default export, so this line is dead code — remove it.
  • superset-frontend/packages/superset-ui-core/src/connection/SupersetClientClass.ts - 1
    • Unnecessary body parse on 400 · Line 57-58
      `isCsrfError` parses the body of every 400 response via `clone().json()`, even for non-JSON error pages (HTML/plain text) that can never be CSRF errors. Consider gating on the `content-type` header before reading the body to avoid an unnecessary body read + JSON parse on the common 400 error path.
  • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.test.tsx - 1
    • Vacuous render test · Line 44-54
      This 'should render' test only asserts `container` is in the document and passes `extra: null`, but `CsrfErrorMessage` destructures only `{ level, message }` and never reads `extra`. It's a copy-paste from `DatabaseErrorMessage.test.tsx` where `extra` is actually consumed, so it exercises no component logic. Consider asserting the rendered title/message or removing it.
  • tests/unit_tests/views/test_error_handling.py - 1
    • Disallow Any in **kwargs · Line 357-357
      `**kwargs: Any` is disallowed by ANN401. Use `**kwargs: object` or a more specific type to maintain type safety.
Review Details
  • Files reviewed - 13 · Commit Range: 92df00d..92df00d
    • superset-frontend/packages/superset-ui-core/src/connection/SupersetClientClass.ts
    • superset-frontend/packages/superset-ui-core/src/connection/constants.ts
    • superset-frontend/packages/superset-ui-core/src/query/api/v1/types.ts
    • superset-frontend/packages/superset-ui-core/src/query/types/Query.ts
    • superset-frontend/packages/superset-ui-core/test/connection/SupersetClientCsrfRecovery.test.ts
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.test.tsx
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx
    • superset-frontend/src/components/ErrorMessage/index.tsx
    • superset-frontend/src/setup/setupErrorMessages.ts
    • superset/errors.py
    • superset/utils/error_sanitization.py
    • superset/views/error_handling.py
    • tests/unit_tests/views/test_error_handling.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
    • Eslint (Linter) - ✔︎ 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

AI Code Review powered by Bito Logo

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 4, 2026
@rusackas

rusackas commented Sep 4, 2026

Copy link
Copy Markdown
Member

Hey @saurabhdamle11, this looks solid, the CSRF_ERROR type plus the shared refresh promise and single-retry cap match what's in #43550, and the tests cover the concurrent-refresh and give-up-after-one-replay cases well. GitHub shows conflicts with master though, so it needs a rebase before it can merge. Holler once that's sorted and I'll take another look.

Signed-off-by: saurabhdamle11 <[email protected]>
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 4, 2026
@saurabhdamle11

Copy link
Copy Markdown
Contributor Author

@rusackas rebased onto master and force-pushed, conflicts are resolved. Whenever you get a chance, pls take a look. Thanks!

@bito-code-review

bito-code-review Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #2ce1ea

Actionable Suggestions - 0
Review Details
  • Files reviewed - 13 · Commit Range: 8968c62..ac6d5c1
    • superset-frontend/packages/superset-ui-core/src/connection/SupersetClientClass.ts
    • superset-frontend/packages/superset-ui-core/src/connection/constants.ts
    • superset-frontend/packages/superset-ui-core/src/query/api/v1/types.ts
    • superset-frontend/packages/superset-ui-core/src/query/types/Query.ts
    • superset-frontend/packages/superset-ui-core/test/connection/SupersetClientCsrfRecovery.test.ts
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.test.tsx
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx
    • superset-frontend/src/components/ErrorMessage/index.tsx
    • superset-frontend/src/setup/setupErrorMessages.ts
    • superset/errors.py
    • superset/utils/error_sanitization.py
    • superset/views/error_handling.py
    • tests/unit_tests/views/test_error_handling.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
    • Eslint (Linter) - ✔︎ 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

AI Code Review powered by Bito Logo

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Sep 9, 2026
@netlify

netlify Bot commented Sep 9, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 9c0a5f0
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa1dcbd2fcd7b0008deadda
😎 Deploy Preview https://deploy-preview-43655--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.

@bito-code-review

bito-code-review Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ba3cc5

Actionable Suggestions - 0
Review Details
  • Files reviewed - 1 · Commit Range: ac6d5c1..9c0a5f0
    • superset-frontend/src/components/ErrorMessage/CsrfErrorMessage.tsx
  • Files skipped - 1
    • docs/static/resources/openapi.json - Reason: Filter setting
  • Tools
    • 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

AI Code Review powered by Bito Logo

@rusackas
rusackas merged commit 61a5d0e into apache:master Sep 22, 2026
84 of 86 checks passed
rusackas added a commit to wuhyn/superset that referenced this pull request Sep 22, 2026
CI's messages.pot drift check was failing on this PR (and on master
generally) because apache#43655's CSRF-recovery strings ("Reload the page and
try again to continue.", "Security token error", "The CSRF token could
not be validated.") were never synced into messages.pot or the .po
catalogs. Regenerated with the pinned Babel/jinja2 toolchain via
scripts/translations/babel_update.sh; verified no existing translations
regressed (translated/fuzzy counts unchanged across all 28 catalogs,
only the 3 new strings land untranslated).

Co-Authored-By: Evan Rusackas <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
rusackas added a commit to wuhyn/superset that referenced this pull request Sep 22, 2026
CI's messages.pot drift check was failing on this PR (and on master
generally) because apache#43655's CSRF-recovery strings ("Reload the page and
try again to continue.", "Security token error", "The CSRF token could
not be validated.") were never synced into messages.pot or the .po
catalogs. Regenerated with the pinned Babel/jinja2 toolchain via
scripts/translations/babel_update.sh; verified no existing translations
regressed (translated/fuzzy counts unchanged across all 28 catalogs,
only the 3 new strings land untranslated).

Co-Authored-By: Evan Rusackas <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
villebro pushed a commit that referenced this pull request Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

authentication Related to authentication change:backend Requires changing the backend change:frontend Requires changing the frontend doc Namespace | Anything related to documentation packages size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Expired CSRF token causes JSON API mutations to fail without recovery

2 participants