You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "Vitor-Avila (via GitHub)" <gi...@apache.org> on 2026/05/12 15:38:26 UTC

[PR] fix(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Vitor-Avila opened a new pull request, #40071:
URL: https://github.com/apache/superset/pull/40071

   ### SUMMARY
   This PR fixes a very rare race condition that could happen with the OAuth2 flow. When loading a dashboard powered by a DB connection authenticated with OAuth2, multiple requests would hit `get_oauth2_access_token`, load the existing OAuth2 token for the user, and if needed call `refresh_oauth2_token`. We currently have a lock to prevent several requests from hitting `refresh_oauth2_token` in parallel, however there was still an edge case where:
   1. Request A is fired, hits `get_oauth2_access_token`, loads the token, check that it's expired and accesses `refresh_oauth2_token` passing this token, acquiring a lock.
   2. Request B is fired, hits `get_oauth2_access_token` and loads the token.
   3. Request A completes `refresh_oauth2_token` and delete the token as part of the process, releasing the lock.
   4. Request B hits `refresh_oauth2_token` passing the token loaded in step 2.
   5. When trying to access one of the token properties, the token is actually deleted.
   
   The fix is to get the token again in `refresh_oauth2_token`.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   No UI changes.
   
   ### TESTING INSTRUCTIONS
   Tests updated and new test added.
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] 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
   


-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40071:
URL: https://github.com/apache/superset/pull/40071#issuecomment-4432220011

   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


Re: [PR] fix(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #40071:
URL: https://github.com/apache/superset/pull/40071#issuecomment-4432232233

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 47676a35eb4cddd1b58565a4fad8165916732364 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a034971c41eb900083799f4 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-40071--superset-docs-preview.netlify.app](https://deploy-preview-40071--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQwMDcxLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.XRdxCaIPyzTywUwNRuDr019kqsEtEbvxY2rCzHlwhFg)<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#DcpLCoAgFADAu7x1kqVkdoOO4TeF8okoFNHdczeLeSEXvHKFDWAAXVQyodvHe0TVaphJUcYRg8nGGjER3Y4ercsnPrvtdVGUcSkmwyenJaV0ZUJKz-H7AQ) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-40071--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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila merged PR #40071:
URL: https://github.com/apache/superset/pull/40071


-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40071:
URL: https://github.com/apache/superset/pull/40071#issuecomment-4456034229

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40071:
URL: https://github.com/apache/superset/pull/40071#issuecomment-4432318067

   <!-- Bito Reply -->
   The flagged issue is valid: after re-querying the token under the lock, the code checks only if the row exists but not if refresh_token is present. If refresh_token is None, calling get_oauth2_fresh_token can trigger an error that deletes the token unnecessarily. To resolve, add a guard for missing refresh_token after the re-query. Here's the concise fix:
   
   **superset/utils/oauth2.py**
   ```
   # Short circuit in case another request already deleted the token
           token = (
               db.session.query(DatabaseUserOAuth2Tokens)
               .filter_by(user_id=user_id, database_id=database_id)
               .one_or_none()
           )
           if token is None:
               return None
           if token.refresh_token is None:
               return None
   
           try:
               token_response = db_engine_spec.get_oauth2_fresh_token(
                   config,
                   token.refresh_token
               )
   ```


-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #40071:
URL: https://github.com/apache/superset/pull/40071#issuecomment-4432354727

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/40071?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `0%` with `5 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 55.27%. Comparing base ([`c394405`](https://app.codecov.io/gh/apache/superset/commit/c394405fc1884b8ef276b3561c08306895e5f67d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`47676a3`](https://app.codecov.io/gh/apache/superset/commit/47676a35eb4cddd1b58565a4fad8165916732364?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 4 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/40071?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/utils/oauth2.py](https://app.codecov.io/gh/apache/superset/pull/40071?src=pr&el=tree&filepath=superset%2Futils%2Foauth2.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdXRpbHMvb2F1dGgyLnB5) | 0.00% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40071?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   > :exclamation:  There is a different number of reports uploaded between BASE (c394405) and HEAD (47676a3). Click for more details.
   > 
   > <details><summary>HEAD has 9 uploads less than BASE</summary>
   >
   >| Flag | BASE (c394405) | HEAD (47676a3) |
   >|------|------|------|
   >|python|10|1|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #40071      +/-   ##
   ==========================================
   - Coverage   64.08%   55.27%   -8.81%     
   ==========================================
     Files        2590     2590              
     Lines      137963   137967       +4     
     Branches    31998    31999       +1     
   ==========================================
   - Hits        88408    76261   -12147     
   - Misses      48037    61044   +13007     
   + Partials     1518      662     -856     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.04% <0.00%> (-0.01%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.04% <0.00%> (-19.48%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/40071/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/40071?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40071:
URL: https://github.com/apache/superset/pull/40071#discussion_r3227878648


##########
superset/utils/oauth2.py:
##########
@@ -129,15 +129,26 @@ def refresh_oauth2_token(
     database_id: int,
     user_id: int,
     db_engine_spec: type[BaseEngineSpec],
-    token: DatabaseUserOAuth2Tokens,
 ) -> str | None:
+    # pylint: disable=import-outside-toplevel
+    from superset.models.core import DatabaseUserOAuth2Tokens
+
     # Use longer TTL for OAuth2 token refresh (may involve network calls)
     with DistributedLock(
         namespace="refresh_oauth2_token",
         ttl_seconds=30,
         user_id=user_id,
         database_id=database_id,
     ):
+        # Short circuit in case another request already deleted the token
+        token = (
+            db.session.query(DatabaseUserOAuth2Tokens)
+            .filter_by(user_id=user_id, database_id=database_id)
+            .one_or_none()
+        )
+        if token is None:
+            return None
+

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing concurrency check in token refresh</b></div>
   <div id="fix">
   
   The refresh_oauth2_token function now fetches the token inside the lock but lacks a check for whether the access token is already valid (not expired). In concurrent requests, this causes redundant refresh calls even if another thread already refreshed the token, leading to performance issues and potential failures with single-use refresh tokens. Add the validity check to short-circuit and return early if the token is still fresh.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
               return None
   
           if token.access_token and datetime.now() < token.access_token_expiration:
               return token.access_token
   
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #46ddfb</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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(OAuth2): Re-query the OAuth2 token to avoid stale reference [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 #40071:
URL: https://github.com/apache/superset/pull/40071#discussion_r3227835254


##########
superset/utils/oauth2.py:
##########
@@ -129,15 +129,26 @@ def refresh_oauth2_token(
     database_id: int,
     user_id: int,
     db_engine_spec: type[BaseEngineSpec],
-    token: DatabaseUserOAuth2Tokens,
 ) -> str | None:
+    # pylint: disable=import-outside-toplevel
+    from superset.models.core import DatabaseUserOAuth2Tokens
+
     # Use longer TTL for OAuth2 token refresh (may involve network calls)
     with DistributedLock(
         namespace="refresh_oauth2_token",
         ttl_seconds=30,
         user_id=user_id,
         database_id=database_id,
     ):
+        # Short circuit in case another request already deleted the token
+        token = (
+            db.session.query(DatabaseUserOAuth2Tokens)
+            .filter_by(user_id=user_id, database_id=database_id)
+            .one_or_none()
+        )
+        if token is None:
+            return None

Review Comment:
   **Suggestion:** After re-querying the token under the lock, the code only checks whether the row exists, but not whether `refresh_token` is still present. Since `refresh_token` is nullable and can legitimately be `None`, this can call `get_oauth2_fresh_token` with a null token and trigger an OAuth error path that deletes the row unnecessarily. Add a post-requery guard for missing `refresh_token` (and return `None` without refreshing) before invoking the engine spec. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Dashboard and SQL queries fail during concurrent OAuth2 refresh.
   - ⚠️ Users forced to re-authenticate despite recent OAuth2 login.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Trigger a database connection using OAuth2 in `Database.get_sqla_engine()` at
   `superset/models/core.py:33-43` by loading a dashboard or chart backed by an
   OAuth2-enabled database; this calls `get_oauth2_access_token(oauth2_config, self.id,
   g.user.id, self.db_engine_spec)` at line 35.
   
   2. Ensure there is an existing row in `database_user_oauth2_tokens` with a valid
   `refresh_token` and an expired `access_token` for this `(user_id, database_id)` pair,
   created by `OAuth2StoreTokenCommand.run()` at
   `superset/commands/database/oauth2.py:48-58`, which stores
   `refresh_token=token_response.get("refresh_token")`.
   
   3. When `get_oauth2_access_token` runs at `superset/utils/oauth2.py:107-119`, it loads the
   token row, sees that `access_token` is expired, and since `token.refresh_token` is truthy
   at line 118, it calls `refresh_oauth2_token(config, database_id, user_id, db_engine_spec)`
   at line 119.
   
   4. In parallel, invoke the OAuth2 callback API `/api/v1/database/...` handled in
   `superset/databases/api.py:20-22`, which constructs `OAuth2StoreTokenCommand(parameters)`
   and calls `command.run()`. This command deletes any existing token via
   `DatabaseUserOAuth2TokensDAO.delete([existing])` at
   `superset/commands/database/oauth2.py:41-47` and creates a new token row with
   `refresh_token=token_response.get("refresh_token")` at lines 48-57; for providers that do
   not return a refresh token, this new row has `refresh_token=None`.
   
   5. Back in `refresh_oauth2_token` at `superset/utils/oauth2.py:48-71`, after acquiring the
   `DistributedLock`, the code re-queries the token (`token =
   db.session.query(DatabaseUserOAuth2Tokens)...one_or_none()` at lines 65-69) and only
   checks `if token is None: return None` at lines 70-71, not whether `token.refresh_token`
   is still present; in the concurrent scenario, this re-query can return the new row with
   `refresh_token=None`.
   
   6. `refresh_oauth2_token` then unconditionally calls
   `db_engine_spec.get_oauth2_fresh_token(config, token.refresh_token)` at
   `superset/utils/oauth2.py:73-77`. With `token.refresh_token` now `None`, the engine spec
   can raise its `oauth2_exception`, triggering the handler at lines 78-87 that logs the
   error, deletes the token row (`db.session.delete(token)`), flushes, and re-raises, causing
   the calling request's database connection attempt to fail and unnecessarily deleting the
   newly stored token.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Futils%2Foauth2.py%0A%2A%2ALine%3A%2A%2A%20143%3A150%0A%2A%2AComment%3A%2A%2A%0A%09%2AIncorrect%20Condition%20Logic%3A%20After%20re-querying%20the%20token%20under%20the%20lock%2C%20the%20code%20only%20checks%20whether%20the%20row%20exists%2C%20but%20not%20whether%20%60refresh_token%60%20is%20still%20present.%20Since%20%60refresh_token%60%20is%20nullable%20and%20can%20legitimately%20be%20%60None%60%2C%20this%20can%20call%20%60get_oauth2_fresh_token%60%20with%20a%20null%20token%20and%20trigger%20an%20OAuth%20error%20path%20that%20deletes%20the%20row%20unnecessarily.%20Add%20a%20post-requery%20guard%20for%20missing%20%60refresh_token%60%20%28and%20return%20%60None%60%20without%20refreshing%29%20before%20invoking%20the%20engine%20spec.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20Ho
 w%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Futils%2Foauth2.py%0A%2A%2ALine%3A%2A%2A%20143%3A150%0A%2A%2AComment%3A%2A%2A%0A%09%2AIncorrect%20Condition%20Logic%3A%20After%20re-querying%20the%20token%20under%20the%20lock%2C%20the%20code%20only%20checks%20whether%20the%20row%20exists%2C%20but%20not%20whether%20%60refresh_token%60%20is%20still%20present.%20Since%20%60refresh_token%60%20is%20nullable%20and%
 20can%20legitimately%20be%20%60None%60%2C%20this%20can%20call%20%60get_oauth2_fresh_token%60%20with%20a%20null%20token%20and%20trigger%20an%20OAuth%20error%20path%20that%20deletes%20the%20row%20unnecessarily.%20Add%20a%20post-requery%20guard%20for%20missing%20%60refresh_token%60%20%28and%20return%20%60None%60%20without%20refreshing%29%20before%20invoking%20the%20engine%20spec.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/utils/oauth2.py
   **Line:** 143:150
   **Comment:**
   	*Incorrect Condition Logic: After re-querying the token under the lock, the code only checks whether the row exists, but not whether `refresh_token` is still present. Since `refresh_token` is nullable and can legitimately be `None`, this can call `get_oauth2_fresh_token` with a null token and trigger an OAuth error path that deletes the row unnecessarily. Add a post-requery guard for missing `refresh_token` (and return `None` without refreshing) before invoking the engine spec.
   
   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%2F40071&comment_hash=0cee6dd3144601665d64af98df8d7c344b34911c5bae74e07faf52ec96c9ab8c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40071&comment_hash=0cee6dd3144601665d64af98df8d7c344b34911c5bae74e07faf52ec96c9ab8c&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(OAuth2): Re-query the OAuth2 token to avoid stale reference [superset]

Posted by "betodealmeida (via GitHub)" <gi...@apache.org>.
betodealmeida commented on code in PR #40071:
URL: https://github.com/apache/superset/pull/40071#discussion_r3228106055


##########
superset/utils/oauth2.py:
##########
@@ -129,15 +129,26 @@ def refresh_oauth2_token(
     database_id: int,
     user_id: int,
     db_engine_spec: type[BaseEngineSpec],
-    token: DatabaseUserOAuth2Tokens,
 ) -> str | None:
+    # pylint: disable=import-outside-toplevel
+    from superset.models.core import DatabaseUserOAuth2Tokens
+
     # Use longer TTL for OAuth2 token refresh (may involve network calls)
     with DistributedLock(
         namespace="refresh_oauth2_token",
         ttl_seconds=30,
         user_id=user_id,
         database_id=database_id,
     ):
+        # Short circuit in case another request already deleted the token
+        token = (
+            db.session.query(DatabaseUserOAuth2Tokens)
+            .filter_by(user_id=user_id, database_id=database_id)
+            .one_or_none()
+        )
+        if token is None:
+            return None

Review Comment:
   Yeah, I like this comment and the one below. If we fetch a token, let's recheck if it's  valid (return it if so) or if it doesn't have a refresh token (return `None` if so).



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