Skip to content

fix(oauth2): Fixing issue with oauth2 manual and auto refresh#7573

Open
RVBastien wants to merge 1 commit intousebruno:mainfrom
RVBastien:bugfix/oauth2-refresh
Open

fix(oauth2): Fixing issue with oauth2 manual and auto refresh#7573
RVBastien wants to merge 1 commit intousebruno:mainfrom
RVBastien:bugfix/oauth2-refresh

Conversation

@RVBastien
Copy link
Copy Markdown

@RVBastien RVBastien commented Mar 25, 2026

Description

This change fixes Bruno's OAuth2 refresh flow.

What changed

  • refreshOauth2Token() now separates:
    • the URL used to read/write cached credentials
    • the URL used to send the refresh request
  • the refresh callers now treat a refresh result without an access_token as a failed refresh

Why

  • cached OAuth2 credentials are stored under the access token URL
  • when refreshTokenUrl differs from accessTokenUrl, looking up cached credentials with the refresh URL can prevent Bruno from finding the stored refresh_token, so no refresh request is made
  • refreshOauth2Token() can fail by returning credentials: null, not only by throwing, so callers need to handle that case explicitly

Result

  • refresh works correctly when access and refresh endpoints are different
  • failed refresh results are handled correctly by the existing OAuth2 flow

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • [x ] The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • Bug Fixes

    • Improved OAuth2 token refresh validation with proper error handling for failed refresh attempts.
  • Refactor

    • Enhanced internal OAuth2 token refresh flow for improved reliability and error recovery.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 25, 2026

Walkthrough

Modified OAuth2 token refresh logic to introduce validation checking for successful credential acquisition and refactored URL handling to distinguish between credential cache operations and refresh HTTP requests across three authorization flows.

Changes

Cohort / File(s) Summary
OAuth2 Token Refresh Validation & URL Handling
packages/bruno-electron/src/utils/oauth2.js
Added post-refresh validation throwing Error('OAuth2 token refresh failed') when credentials.access_token is missing in authorization-code, client-credentials, and password-certificate flows. Refactored URL handling to separate cacheUrl (credential storage/retrieval) from refreshUrl (HTTP refresh request), replacing previous single url parameter usage.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

  • #6164 — Modifies OAuth2 token refresh signatures and adds per-token/refresh configuration; overlaps with this PR's refresh logic changes in the same module.

Suggested labels

size/L

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

🔐 Two URLs walk into the OAuth flow,
One caches, one refreshes—now we know!
When tokens falter, validation stands tall,
Catching the empty and returning it all. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: fixing OAuth2 refresh flow issues. It directly relates to the primary modifications in the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-electron/src/utils/oauth2.js`:
- Around line 698-705: The current flow persists only the fresh token response
from getCredentialsFromTokenUrl, which can drop unchanged fields like
refresh_token; instead, load the existing cached credentials for the given
collectionUid/cacheUrl/credentialsId, merge the existing credential object with
the new credentials (new values overwrite cached ones but preserve any fields
missing from the response), then call persistOauth2Credentials with the merged
object; keep the existing clearOauth2Credentials path when credentials is falsy
or has error and continue returning the same tuple (collectionUid, url:
cacheUrl, credentials, credentialsId, debugInfo).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1d9ccb0d-3a9e-408c-8118-54b94014d1bd

📥 Commits

Reviewing files that changed from the base of the PR and between 304f6c8 and 55cd48c.

📒 Files selected for processing (1)
  • packages/bruno-electron/src/utils/oauth2.js

Comment on lines 698 to +705
const { credentials, requestDetails } = await getCredentialsFromTokenUrl({ requestConfig: axiosRequestConfig, certsAndProxyConfig });
debugInfo.data.push(requestDetails);
if (!credentials || credentials?.error) {
clearOauth2Credentials({ collectionUid, url, credentialsId });
return { collectionUid, url, credentials: null, credentialsId, debugInfo };
clearOauth2Credentials({ collectionUid, url: cacheUrl, credentialsId });
return { collectionUid, url: cacheUrl, credentials: null, credentialsId, debugInfo };
}
credentials && persistOauth2Credentials({ collectionUid, url, credentials, credentialsId });
return { collectionUid, url, credentials, credentialsId, debugInfo };
credentials && persistOauth2Credentials({ collectionUid, url: cacheUrl, credentials, credentialsId });
return { collectionUid, url: cacheUrl, credentials, credentialsId, debugInfo };
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Merge refresh responses with the cached credentials before persisting.

Some OAuth2 servers do not repeat unchanged fields on refresh. Persisting only the response payload here can drop the cached refresh_token and make the next refresh fail even though this one succeeded.

Proposed fix
-      if (!credentials || credentials?.error) {
+      if (!credentials || credentials?.error || !credentials.access_token) {
         clearOauth2Credentials({ collectionUid, url: cacheUrl, credentialsId });
         return { collectionUid, url: cacheUrl, credentials: null, credentialsId, debugInfo };
       }
-      credentials && persistOauth2Credentials({ collectionUid, url: cacheUrl, credentials, credentialsId });
-      return { collectionUid, url: cacheUrl, credentials, credentialsId, debugInfo };
+      const refreshedCredentials = {
+        ...storedCredentials,
+        ...credentials,
+        refresh_token: credentials.refresh_token ?? storedCredentials.refresh_token
+      };
+      persistOauth2Credentials({ collectionUid, url: cacheUrl, credentials: refreshedCredentials, credentialsId });
+      return { collectionUid, url: cacheUrl, credentials: refreshedCredentials, credentialsId, debugInfo };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/utils/oauth2.js` around lines 698 - 705, The
current flow persists only the fresh token response from
getCredentialsFromTokenUrl, which can drop unchanged fields like refresh_token;
instead, load the existing cached credentials for the given
collectionUid/cacheUrl/credentialsId, merge the existing credential object with
the new credentials (new values overwrite cached ones but preserve any fields
missing from the response), then call persistOauth2Credentials with the merged
object; keep the existing clearOauth2Credentials path when credentials is falsy
or has error and continue returning the same tuple (collectionUid, url:
cacheUrl, credentials, credentialsId, debugInfo).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant