diff --git a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js index f64b4937312..534f9e2d385 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js +++ b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js @@ -18,7 +18,11 @@ import toast from 'react-hot-toast'; const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAuth, collection, folder }) => { const dispatch = useDispatch(); const preferences = useSelector((state) => state.app.preferences); - const { storedTheme } = useTheme(); + const { storedTheme, theme } = useTheme(); + const tooltipStyle = { + backgroundColor: theme?.background?.surface0, + color: theme?.text + }; const useSystemBrowser = get(preferences, 'request.oauth2.useSystemBrowser', false); const { isSensitive } = useDetectSensitiveField(collection); const oAuth = get(request, 'auth.oauth2', {}); @@ -182,13 +186,23 @@ const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAu {inputsConfig.map((input) => { - const { key, label, isSecret } = input; + const { key, label, isSecret, tooltip } = input; const value = oAuth[key] || ''; const { showWarning, warningMessage } = isSensitive(value); return (
- +
- + Automatically fetch a new token when you try to access a resource and don't have one.
@@ -390,7 +404,7 @@ const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAu
- + Automatically refresh your token using the refresh URL when it expires.
diff --git a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js index 89b822c6b1b..6018d322d43 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js +++ b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js @@ -22,7 +22,8 @@ const inputsConfig = [ }, { key: 'state', - label: 'State' + label: 'State', + tooltip: 'If left empty, Bruno automatically generates a secure random value to help protect against CSRF attacks.' } ]; diff --git a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js index 1591a5be6a8..d372ecb06dc 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js +++ b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js @@ -5,7 +5,10 @@ import { cloneDeep, find, get } from 'lodash'; import { IconLoader2, IconX } from '@tabler/icons'; import { interpolate } from '@usebruno/common'; import { fetchOauth2Credentials, clearOauth2Cache, refreshOauth2Credentials, cancelOauth2AuthorizationRequest, isOauth2AuthorizationRequestInProgress } from 'providers/ReduxStore/slices/collections/actions'; +import { responseReceived } from 'providers/ReduxStore/slices/collections'; +import { updateResponsePaneTab } from 'providers/ReduxStore/slices/tabs'; import { getAllVariables } from 'utils/collections/index'; +import { formatIpcError } from 'utils/common/error'; import Button from 'ui/Button'; const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, credentialsId }) => { @@ -41,6 +44,23 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c const credentialsData = find(collection?.oauth2Credentials, (creds) => creds?.url == interpolatedAccessTokenUrl && creds?.collectionUid == collectionUid && creds?.credentialsId == credentialsId); const creds = credentialsData?.credentials || {}; + const showOauth2Error = (errorMessage) => { + dispatch( + responseReceived({ + itemUid: item.uid, + collectionUid, + response: { + error: errorMessage, + isError: true, + status: 'Error', + size: 0, + duration: 0 + } + }) + ); + dispatch(updateResponsePaneTab({ uid: item.uid, responsePaneTab: 'response' })); + }; + const handleFetchOauth2Credentials = async () => { let requestCopy = cloneDeep(request); requestCopy.oauth2 = requestCopy?.auth.oauth2; @@ -59,6 +79,7 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c const errorMessage = result?.error || 'No access token received from authorization server'; console.error(errorMessage); toast.error(errorMessage); + showOauth2Error(errorMessage); return; } @@ -70,7 +91,9 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c if (error?.message && error.message.includes('cancelled by user')) { return; } - toast.error(error?.message || 'An error occurred while fetching token!'); + const errorMessage = formatIpcError(error) || 'An error occurred while fetching token!'; + toast.error(errorMessage); + showOauth2Error(errorMessage); } finally { toggleFetchingToken(false); toggleFetchingAuthorizationCode(false); @@ -104,7 +127,8 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c } catch (error) { console.error(error); toggleRefreshingToken(false); - toast.error(error?.message || 'An error occurred while refreshing token!'); + const errorMessage = formatIpcError(error) || 'An error occurred while refreshing token!'; + toast.error(errorMessage); } }; diff --git a/packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js b/packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js index 23705b827d1..d9923e19c79 100644 --- a/packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js +++ b/packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js @@ -1,7 +1,7 @@ const { shell } = require('electron'); const { registerOauth2AuthorizationRequest, rejectOauth2AuthorizationRequest } = require('../../utils/oauth2-protocol-handler'); -const authorizeUserInSystemBrowser = ({ authorizeUrl, callbackUrl, grantType = 'authorization_code' }) => { +const authorizeUserInSystemBrowser = ({ authorizeUrl, callbackUrl, grantType = 'authorization_code', expectedState = null }) => { return new Promise((resolve, reject) => { // Replace callback URL in authorization URL const authorizationUrlObj = new URL(authorizeUrl); @@ -51,7 +51,7 @@ const authorizeUserInSystemBrowser = ({ authorizeUrl, callbackUrl, grantType = ' reject(error); }; - registerOauth2AuthorizationRequest(wrappedResolve, wrappedReject, debugInfo); + registerOauth2AuthorizationRequest(wrappedResolve, wrappedReject, debugInfo, expectedState); // Open system browser shell.openExternal(modifiedAuthorizeUrl).catch((error) => { diff --git a/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js b/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js index e8ecf994b7d..49ff58aa916 100644 --- a/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js +++ b/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js @@ -1,5 +1,6 @@ const { BrowserWindow } = require('electron'); const { preferencesUtil } = require('../../store/preferences'); +const { getParamFromUrl } = require('../../utils/common'); const matchesCallbackUrl = (url, callbackUrl) => { if (!url) return false; @@ -11,7 +12,7 @@ const matchesCallbackUrl = (url, callbackUrl) => { && (url.searchParams.has('code') || url.hash.length > 1); }; -const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalHeaders = {}, grantType = 'authorization_code' }) => { +const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalHeaders = {}, grantType = 'authorization_code', expectedState = null }) => { return new Promise(async (resolve, reject) => { let finalUrl = null; let debugInfo = { @@ -202,6 +203,18 @@ const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalH if (finalUrl) { try { + // Validate the state parameter to protect against CSRF / authorization + // code injection. State is always issued when a flow is initiated, so a + // missing expected or returned state means a forged/invalid callback — + // fail closed. + const finalUrlObj = new URL(finalUrl); + const returnedState = getParamFromUrl(finalUrlObj, 'state'); + if (!expectedState || returnedState !== expectedState) { + return reject( + new Error('OAuth2 state mismatch: the returned state does not match the issued state.') + ); + } + // Handle different grant types differently if (grantType === 'implicit') { // For implicit flow, tokens are in the URL hash fragment diff --git a/packages/bruno-electron/src/utils/common.js b/packages/bruno-electron/src/utils/common.js index 384410ea883..a3df0c1d161 100644 --- a/packages/bruno-electron/src/utils/common.js +++ b/packages/bruno-electron/src/utils/common.js @@ -150,6 +150,15 @@ const parseDataFromRequest = (request) => { return parseDataFromResponse(requestCopy); }; +// Read a param from the query string, falling back to the URL hash fragment +// (implicit flow returns values in the hash rather than query params). +const getParamFromUrl = (urlObj, param) => { + return ( + urlObj.searchParams.get(param) + || (urlObj.hash ? new URLSearchParams(urlObj.hash.substring(1)).get(param) : null) + ); +}; + module.exports = { uuid, stringifyJson, @@ -160,5 +169,6 @@ module.exports = { generateUidBasedOnHash, flattenDataForDotNotation, parseDataFromResponse, - parseDataFromRequest + parseDataFromRequest, + getParamFromUrl }; diff --git a/packages/bruno-electron/src/utils/oauth2-protocol-handler.js b/packages/bruno-electron/src/utils/oauth2-protocol-handler.js index 3d998e1bfb9..397334a0cc6 100644 --- a/packages/bruno-electron/src/utils/oauth2-protocol-handler.js +++ b/packages/bruno-electron/src/utils/oauth2-protocol-handler.js @@ -1,6 +1,8 @@ +const { getParamFromUrl } = require('./common'); + let oauth2AuthorizationRequest = null; -const registerOauth2AuthorizationRequest = (resolve, reject, debugInfo = null) => { +const registerOauth2AuthorizationRequest = (resolve, reject, debugInfo = null, expectedState = null) => { // Cancel any existing pending request if (oauth2AuthorizationRequest) { oauth2AuthorizationRequest.reject(new Error('Authorization cancelled: new request started')); @@ -10,6 +12,7 @@ const registerOauth2AuthorizationRequest = (resolve, reject, debugInfo = null) = resolve, reject, debugInfo, + expectedState, timestamp: Date.now() }; }; @@ -67,8 +70,8 @@ const handleOauth2ProtocolUrl = (url) => { } // Check for errors in query params (authorization code flow) or hash (implicit flow) - const error = urlObj.searchParams.get('error') || (urlObj.hash ? new URLSearchParams(urlObj.hash.substring(1)).get('error') : null); - const errorDescription = urlObj.searchParams.get('error_description') || (urlObj.hash ? new URLSearchParams(urlObj.hash.substring(1)).get('error_description') : null); + const error = getParamFromUrl(urlObj, 'error'); + const errorDescription = getParamFromUrl(urlObj, 'error_description'); if (error) { const errorData = { @@ -80,6 +83,19 @@ const handleOauth2ProtocolUrl = (url) => { return; } + // Validate the state parameter to protect against CSRF / authorization code + // injection. State is always issued when a flow is initiated, so a missing + // expected or returned state means a forged/invalid callback — fail closed. + const expectedState = oauth2AuthorizationRequest?.expectedState; + const returnedState = getParamFromUrl(urlObj, 'state'); + + if (!expectedState || returnedState !== expectedState) { + rejectOauth2AuthorizationRequest( + new Error('OAuth2 state mismatch: the returned state does not match the issued state.') + ); + return; + } + // Check if this is an implicit grant (tokens in hash fragment) if (urlObj.hash) { const hash = urlObj.hash.substring(1); // Remove the leading # diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index 6af08a41b67..ddef799f8b6 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -308,6 +308,10 @@ const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => { const { callbackUrl, clientId, authorizationUrl, scope, state, pkce, accessTokenUrl, additionalParameters } = oauth2; const useSystemBrowser = preferencesUtil.shouldUseSystemBrowser(); const effectiveCallbackUrl = callbackUrl && callbackUrl.length ? callbackUrl : BRUNO_OAUTH2_CALLBACK_URL; + // Always append a cryptographically random nonce to the user-configured state + // (or generate a fully random one when none is set). The state is validated when + // the callback is received to prevent authorization code injection / CSRF. + const effectiveState = generateState({ userState: state }); const authorizationUrlWithQueryParams = new URL(authorizationUrl); authorizationUrlWithQueryParams.searchParams.append('response_type', 'code'); @@ -324,8 +328,8 @@ const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => { authorizationUrlWithQueryParams.searchParams.append('code_challenge', codeChallenge); authorizationUrlWithQueryParams.searchParams.append('code_challenge_method', 'S256'); } - if (state) { - authorizationUrlWithQueryParams.searchParams.append('state', state); + if (effectiveState) { + authorizationUrlWithQueryParams.searchParams.append('state', effectiveState); } if (additionalParameters?.authorization?.length) { additionalParameters.authorization.forEach((param) => { @@ -344,6 +348,7 @@ const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => { authorizeUrl, callbackUrl: effectiveCallbackUrl, session: oauth2Store.getSessionIdOfCollection({ collectionUid, url: accessTokenUrl }), + expectedState: effectiveState, additionalHeaders: getAdditionalHeaders(additionalParameters?.authorization) }); resolve({ authorizationCode, debugInfo }); @@ -707,6 +712,18 @@ const generateCodeVerifier = () => { return crypto.randomBytes(22).toString('hex'); }; +// Build an OAuth2 state string to help prevent CSRF and forged auth codes. +// If the user passes a state, it goes first; we append random bytes after it. +// The user keeps their custom data, and the random suffix keeps the flow secure. +const generateState = ({ userState }) => { + const trimmedUserState = userState?.trim(); + if (trimmedUserState && trimmedUserState.length > 0) { + return trimmedUserState; + } + let cryptographicallyRandomString = crypto.randomBytes(16).toString('hex'); + return cryptographicallyRandomString; +}; + const generateCodeChallenge = (codeVerifier) => { const hash = crypto.createHash('sha256'); hash.update(codeVerifier); @@ -760,6 +777,9 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF } = oauth2; const useSystemBrowser = preferencesUtil.shouldUseSystemBrowser(); const effectiveCallbackUrl = callbackUrl && callbackUrl.length ? callbackUrl : BRUNO_OAUTH2_CALLBACK_URL; + // Use the user-configured state if present, otherwise generate a cryptographically + // random one. The state is validated when the callback is received to prevent CSRF. + const effectiveState = generateState({ userState: state }); // Validate required fields if (!authorizationUrl) { @@ -844,9 +864,8 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF if (scope) { authorizationUrlWithQueryParams.searchParams.append('scope', scope); } - if (state) { - authorizationUrlWithQueryParams.searchParams.append('state', state); - } + authorizationUrlWithQueryParams.searchParams.append('state', effectiveState); + if (additionalParameters?.authorization?.length) { additionalParameters.authorization.forEach((param) => { if (param.enabled && param.name) { @@ -866,6 +885,7 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF callbackUrl: effectiveCallbackUrl, session: oauth2Store.getSessionIdOfCollection({ collectionUid, url: authorizationUrl }), grantType: 'implicit', + expectedState: effectiveState, additionalHeaders: getAdditionalHeaders(additionalParameters?.authorization) }); @@ -954,5 +974,6 @@ module.exports = { refreshOauth2Token, generateCodeVerifier, generateCodeChallenge, + generateState, updateCollectionOauth2Credentials }; diff --git a/packages/bruno-electron/tests/utils/oauth2-protocol-handler.spec.js b/packages/bruno-electron/tests/utils/oauth2-protocol-handler.spec.js new file mode 100644 index 00000000000..10f030ce7fe --- /dev/null +++ b/packages/bruno-electron/tests/utils/oauth2-protocol-handler.spec.js @@ -0,0 +1,135 @@ +const { + registerOauth2AuthorizationRequest, + handleOauth2ProtocolUrl, + cancelOAuth2AuthorizationRequest, + isOauth2AuthorizationRequestInProgress +} = require('../../src/utils/oauth2-protocol-handler'); + +describe('handleOauth2ProtocolUrl - state validation', () => { + let resolve; + let reject; + + beforeEach(() => { + resolve = jest.fn(); + reject = jest.fn(); + }); + + afterEach(() => { + // Clear any pending request between tests + if (isOauth2AuthorizationRequestInProgress()) { + cancelOAuth2AuthorizationRequest(); + } + jest.clearAllMocks(); + }); + + describe('authorization code flow (state in query params)', () => { + it('should resolve with the code when the returned state matches', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback?code=auth-code-123&state=expected-state'); + + expect(resolve).toHaveBeenCalledWith('auth-code-123'); + expect(reject).not.toHaveBeenCalled(); + }); + + it('should reject when the returned state does not match', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback?code=auth-code-123&state=attacker-state'); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('state mismatch') }) + ); + }); + + it('should reject when no state is returned but one was expected', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback?code=auth-code-123'); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('state mismatch') }) + ); + }); + }); + + describe('implicit flow (state in hash fragment)', () => { + it('should resolve with tokens when the returned state matches', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl( + 'bruno://app/oauth2/callback#access_token=token-abc&token_type=bearer&state=expected-state' + ); + + expect(resolve).toHaveBeenCalledWith( + expect.objectContaining({ access_token: 'token-abc' }) + ); + expect(reject).not.toHaveBeenCalled(); + }); + + it('should reject when the hash state does not match', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl( + 'bruno://app/oauth2/callback#access_token=token-abc&token_type=bearer&state=attacker-state' + ); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('state mismatch') }) + ); + }); + + it('should reject when no hash state is returned but one was expected', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl( + 'bruno://app/oauth2/callback#access_token=token-abc&token_type=bearer' + ); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('state mismatch') }) + ); + }); + }); + + describe('when no expected state was registered', () => { + it('should reject rather than resolve without state (fail closed)', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, null); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback?code=auth-code-123'); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('state mismatch') }) + ); + }); + }); + + describe('error responses are handled before state validation', () => { + it('should reject with the provider error even if state is absent', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback?error=access_denied'); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('Authorization Failed') }) + ); + }); + + it('should reject with the provider error in the hash fragment even if state is absent', () => { + registerOauth2AuthorizationRequest(resolve, reject, null, 'expected-state'); + + handleOauth2ProtocolUrl('bruno://app/oauth2/callback#error=access_denied'); + + expect(resolve).not.toHaveBeenCalled(); + expect(reject).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('Authorization Failed') }) + ); + }); + }); +});