Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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', {});
Expand Down Expand Up @@ -182,13 +186,23 @@ const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAu
</div>
</div>
{inputsConfig.map((input) => {
const { key, label, isSecret } = input;
const { key, label, isSecret, tooltip } = input;
const value = oAuth[key] || '';
const { showWarning, warningMessage } = isSensitive(value);

return (
<div className="flex items-center gap-4 w-full" key={`input-${key}`}>
<label className="block min-w-[140px]">{label}</label>
<label className="min-w-[140px] flex items-center gap-4">
{label}
{tooltip && (
<div className="relative group cursor-pointer inline-flex items-center">
<IconHelp size={16} className="text-gray-500" />
<span className="group-hover:opacity-100 pointer-events-none opacity-0 max-w-60 absolute left-0 top-full mt-1 w-max p-2 text-xs rounded-md transition-opacity duration-200 z-10" style={tooltipStyle}>
{tooltip}
</span>
</div>
)}
</label>
<div className="single-line-editor-wrapper flex-1 flex items-center">
<SingleLineEditor
value={value}
Expand Down Expand Up @@ -370,7 +384,7 @@ const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAu
<div className="flex items-center gap-2">
<div className="relative group cursor-pointer">
<IconHelp size={16} className="text-gray-500" />
<span className="group-hover:opacity-100 pointer-events-none opacity-0 max-w-60 absolute left-0 bottom-full mb-1 w-max p-2 bg-gray-700 text-white text-xs rounded-md transition-opacity duration-200">
<span className="group-hover:opacity-100 pointer-events-none opacity-0 max-w-60 absolute left-0 bottom-full mb-1 w-max p-2 text-xs rounded-md transition-opacity duration-200" style={tooltipStyle}>
Automatically fetch a new token when you try to access a resource and don't have one.
</span>
</div>
Expand All @@ -390,7 +404,7 @@ const OAuth2AuthorizationCode = ({ save, item = {}, request, handleRun, updateAu
<div className="flex items-center gap-2">
<div className="relative group cursor-pointer">
<IconHelp size={16} className="text-gray-500" />
<span className="group-hover:opacity-100 pointer-events-none opacity-0 max-w-60 absolute left-0 bottom-full mb-1 w-max p-2 bg-gray-700 text-white text-xs rounded-md transition-opacity duration-200">
<span className="group-hover:opacity-100 pointer-events-none opacity-0 max-w-60 absolute left-0 bottom-full mb-1 w-max p-2 text-xs rounded-md transition-opacity duration-200" style={tooltipStyle}>
Automatically refresh your token using the refresh URL when it expires.
</span>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.'
}
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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) => {
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
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;
Expand All @@ -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);
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
return;
}

Expand All @@ -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);
Comment thread
abhishekp-bruno marked this conversation as resolved.
Resolved
} finally {
toggleFetchingToken(false);
toggleFetchingAuthorizationCode(false);
Expand Down Expand Up @@ -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);
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
}
};

Expand Down
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 = {
Expand Down Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion packages/bruno-electron/src/utils/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -160,5 +169,6 @@ module.exports = {
generateUidBasedOnHash,
flattenDataForDotNotation,
parseDataFromResponse,
parseDataFromRequest
parseDataFromRequest,
getParamFromUrl
};
22 changes: 19 additions & 3 deletions packages/bruno-electron/src/utils/oauth2-protocol-handler.js
Original file line number Diff line number Diff line change
@@ -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'));
Expand All @@ -10,6 +12,7 @@ const registerOauth2AuthorizationRequest = (resolve, reject, debugInfo = null) =
resolve,
reject,
debugInfo,
expectedState,
timestamp: Date.now()
};
};
Expand Down Expand Up @@ -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 = {
Expand All @@ -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 #
Expand Down
31 changes: 26 additions & 5 deletions packages/bruno-electron/src/utils/oauth2.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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) {
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
authorizationUrlWithQueryParams.searchParams.append('state', effectiveState);
}
if (additionalParameters?.authorization?.length) {
additionalParameters.authorization.forEach((param) => {
Expand All @@ -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 });
Expand Down Expand Up @@ -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 }) => {
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
});

Expand Down Expand Up @@ -954,5 +974,6 @@ module.exports = {
refreshOauth2Token,
generateCodeVerifier,
generateCodeChallenge,
generateState,
updateCollectionOauth2Credentials
};
Loading
Loading