Skip to content

fix(snowflake): refresh rejected OAuth tokens - #43623

Merged
aminghadersohi merged 6 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/snowflake-oauth2-force-refresh
Sep 2, 2026
Merged

aminghadersohi merged 6 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/snowflake-oauth2-force-refresh

Conversation

@aminghadersohi

@aminghadersohi aminghadersohi commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Snowflake can reject an otherwise unexpired OAuth2 access token after a Snowflake-side role or grant change. Superset previously treated this as an interactive reauthorization condition, leaving the cached access token in place rather than attempting the stored refresh token.

This change recognizes Snowflake's documented 390303 OAuth access-token error, forces a refresh-token exchange even when the cached access token has not expired, and retries synchronous and asynchronous SQL execution once. A retry context prevents the existing interactive OAuth handler from intercepting the first failure. If silent refresh is unavailable or rejected, the existing interactive authorization flow remains the fallback.

Retries are restricted to engine-classified OAuth errors and are skipped after a multi-statement query has made progress. Attempt, success, and failure counters plus a structured log record provide visibility into forced refreshes.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable; this is a backend-only change.

TESTING INSTRUCTIONS

Run:

PYTHONPATH="$PWD/superset-core/src" pytest -q \
  tests/unit_tests/utils/oauth2_tests.py \
  tests/unit_tests/db_engine_specs/test_snowflake.py

The 151 focused tests verify that:

  • Snowflake error code 390303 and the existing exact error message are classified as OAuth failures.
  • Unrelated Snowflake, network, and timeout errors do not trigger refresh.
  • A valid-but-rejected access token is forcibly refreshed using the stored refresh token.
  • Concurrent failures reuse a winning refresh and never replay a rotated refresh token.
  • Only definitive invalid_grant responses delete stored tokens; transient and ambiguous provider failures preserve them.
  • Execution is retried exactly once.

Pre-commit was also run against every changed file.

ADDITIONAL INFORMATION

  • Has associated issue:
  • 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

Blast radius

This affects database OAuth2 query execution paths only. Forced refresh is reached only when an engine's needs_oauth2() classifier matches; Snowflake's matcher is limited to its DBAPI exception type plus error code 390303 or the existing exact invalid-token message. There are no schema, permissions, RLS, or UI changes.

Risk & rollback

The primary risk is retrying a query after a misclassified error. The Snowflake match is deliberately narrow, and multi-statement executions are not retried after progress is recorded. Rollback is a normal revert of this commit; there are no migrations or persisted-format changes.

Review guidance

Please review superset/utils/oauth2.py first, especially the retry context and forced-refresh fallback behavior, followed by the two SQL execution call sites. The Snowflake matcher change is intentionally limited to the provider's documented access-token-invalid code.

@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.84071% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.22%. Comparing base (abf338d) to head (ccd0df2).
⚠️ Report is 53 commits behind head on master.

Files with missing lines Patch % Lines
superset/utils/oauth2.py 85.71% 10 Missing and 2 partials ⚠️
superset/db_engine_specs/base.py 63.63% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43623      +/-   ##
==========================================
+ Coverage   79.21%   79.22%   +0.01%     
==========================================
  Files        2879     2880       +1     
  Lines      165922   166248     +326     
  Branches    38377    38425      +48     
==========================================
+ Hits       131427   131717     +290     
- Misses      32018    32041      +23     
- Partials     2477     2490      +13     
Flag Coverage Δ
hive 37.86% <8.84%> (-0.08%) ⬇️
mysql 57.52% <10.61%> (-0.16%) ⬇️
postgres 57.55% <10.61%> (-0.17%) ⬇️
presto 39.76% <8.84%> (-0.09%) ⬇️
python 83.77% <85.84%> (+0.02%) ⬆️
sqlite 57.24% <10.61%> (-0.16%) ⬇️
unit 74.21% <85.84%> (+0.24%) ⬆️

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.

@aminghadersohi
aminghadersohi marked this pull request as ready for review August 28, 2026 15:22
@dosubot dosubot Bot added authentication:sso Single Sign On change:backend Requires changing the backend data:connect:snowflake Related to Snowflake labels Aug 28, 2026
Comment thread superset/utils/oauth2.py Resolved
@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. In forced-refresh mode, the token_session is an isolated SQLAlchemy session that requires an explicit commit to persist deletions. Without this commit, the session closes and rolls back the deletion, causing the invalid token to persist and triggering repeated failed refresh attempts.

To resolve this, you should commit the deletion within the token_session before it closes. Here is the suggested fix:

# Inside the forced-refresh block in superset/utils/oauth2.py
# After the deletion logic:
token_session.delete(token)
token_session.commit()  # Ensure the deletion is persisted

I have checked the available PR context, and there are no other comments to address. Would you like me to perform any further analysis?

superset/utils/oauth2.py

token_session.delete(token)
token_session.commit()

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Addressed the open OAuth review feedback in 035cdd3:

  • A forced refresh with no refresh token durably commits deletion from the isolated token session.
  • invalid_grant remains a permanent refresh rejection and raises OAuth2TokenRefreshError; the parser uses the JSON body with a text fallback for compatible provider/test response shapes.
  • Transient or ambiguous provider errors remain non-terminal and preserve the stored refresh token.

Verification: the previously failing GSheets test passes, 189 related unit tests pass, and pre-commit passes for all changed files.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #70b496

Actionable Suggestions - 0
Additional Suggestions - 4
  • superset/utils/oauth2.py - 1
    • Stale identity map on retry · Line 148-148
      The forced refresh commits the new token in an isolated `token_session`, but the caller's `db.session` identity map still holds the stale `DatabaseUserOAuth2Tokens` object loaded during the first attempt. On retry, `get_oauth2_access_token` re-queries `db.session` and returns the rejected/expired token and its already-consumed refresh token, so the retry fails again. Call `db.session.expire_all()` after the forced refresh so the retry re-reads the rotated token.
  • superset/db_engine_specs/base.py - 2
    • OAuth2 dance skipped on retry · Line 2402-2406
      The new `not is_oauth2_retry_active()` guard suppresses the dance for the whole retry window, but `execute_with_oauth2_retry` only starts it on `OAuth2TokenRefreshError` or `access_token is None`. When `can_retry()` is False (e.g. `query.progress > 0` on a multi-statement query), the exception is re-raised at oauth2.py:308 without starting the dance, so the user gets an auth error with no re-auth prompt. Consider starting the dance in that branch.
    • Redundant JSON fallback · Line 980-984
      `response.json()` and `json.loads(response.text)` parse the same text, so when `response.json()` returns a non-dict, the fallback returns the same non-dict and `payload.get("error")` still raises `AttributeError` (caught, `error=None`). The fallback never produces a useful result and is misleading. A single `isinstance(payload, dict)` guard suffices.
  • superset/sql/execution/executor.py - 1
    • Retry shares timeout budget · Line 665-669
      `execute_with_oauth2_retry` re-runs `execute()` on an OAuth2 failure, but the enclosing `utils.timeout` (`SigalrmTimeout`, executor.py:395) arms `signal.alarm(seconds)` once. A retry after a slow first attempt inherits a reduced budget and can be cut off by `SupersetTimeoutException` before the refreshed token completes. Consider re-arming the alarm per attempt.
Review Details
  • Files reviewed - 8 · Commit Range: c288f75..035cdd3
    • superset/db_engine_specs/base.py
    • superset/db_engine_specs/snowflake.py
    • superset/sql/execution/celery_task.py
    • superset/sql/execution/executor.py
    • superset/utils/oauth2.py
    • tests/unit_tests/db_engine_specs/test_base.py
    • tests/unit_tests/db_engine_specs/test_snowflake.py
    • tests/unit_tests/utils/oauth2_tests.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 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

Copy link
Copy Markdown
Member

Heya, one more thing before this can merge, though I want to flag upfront I haven't proven this against the real code, just traced it and confirmed the underlying SQLAlchemy behavior with an isolated repro, so take this as a question to verify rather than a confirmed bug.

execute_with_oauth2_retry loads the token row via the ambient db.session up front for rejected_access_token, but the forced refresh commits on a separate isolated session. On retry, get_oauth2_access_token queries that same ambient db.session again, and since the row's already in its identity map, SQLAlchemy can hand back the stale cached object instead of re-reading the DB, unless something expires it in between. For a query that fails on its first statement (no db.session.commit() has happened yet at that point), I don't see what would expire it, but I haven't run this end to end against a real DB to confirm the retry actually uses the stale token in practice.

Could we add a test that uses two genuinely separate sessions (not Session mocked to equal db.session, like the current force-refresh tests do) and confirms the retried operation sees the new token? If that turns out to be a real gap, a db.session.expire(token) (or expire_all()) right after the forced commit seems like the likely fix, but happy to be wrong here.

Comment thread superset/utils/oauth2.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

@rusackas Fixed in ccd0df2. Added a two-session regression test and expire the ambient token row after the isolated refresh commit, so the retry reads the rotated token.

@netlify

netlify Bot commented Sep 1, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit ccd0df2
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a9643bb34a4d400080444ef
😎 Deploy Preview https://deploy-preview-43623--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 1, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #8b1a2c

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 035cdd3..ccd0df2
    • superset/utils/oauth2.py
    • tests/unit_tests/utils/oauth2_tests.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 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

@aminghadersohi
aminghadersohi merged commit 3394097 into apache:master Sep 2, 2026
73 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

authentication:sso Single Sign On change:backend Requires changing the backend data:connect:snowflake Related to Snowflake size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants