Skip to content

Commit dddbc14

Browse files
feat(oauth2): add clear error handling and streamline OAuth2 flow in tests
- Introduced a new `clearOauth2Error` function to handle error clearing in the OAuth2 action buttons. - Refactored test cases to utilize a common `startOAuth2Flow` function for improved readability and maintainability. - Updated Keycloak configuration to enable public client support for better compatibility.
1 parent 69c0184 commit dddbc14

3 files changed

Lines changed: 51 additions & 56 deletions

File tree

‎packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { cloneDeep, find, get } from 'lodash';
55
import { IconLoader2, IconX } from '@tabler/icons';
66
import { interpolate } from '@usebruno/common';
77
import { fetchOauth2Credentials, clearOauth2Cache, refreshOauth2Credentials, cancelOauth2AuthorizationRequest, isOauth2AuthorizationRequestInProgress } from 'providers/ReduxStore/slices/collections/actions';
8-
import { responseReceived } from 'providers/ReduxStore/slices/collections';
8+
import { responseReceived, responseCleared } from 'providers/ReduxStore/slices/collections';
99
import { updateResponsePaneTab } from 'providers/ReduxStore/slices/tabs';
1010
import { getAllVariables } from 'utils/collections/index';
1111
import { formatIpcError } from 'utils/common/error';
@@ -61,6 +61,10 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c
6161
dispatch(updateResponsePaneTab({ uid: item.uid, responsePaneTab: 'response' }));
6262
};
6363

64+
const clearOauth2Error = () => {
65+
dispatch(responseCleared({ itemUid: item.uid, collectionUid }));
66+
};
67+
6468
const handleFetchOauth2Credentials = async () => {
6569
let requestCopy = cloneDeep(request);
6670
requestCopy.oauth2 = requestCopy?.auth.oauth2;
@@ -83,6 +87,7 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c
8387
return;
8488
}
8589

90+
clearOauth2Error();
8691
toast.success('Token fetched successfully!');
8792
} catch (error) {
8893
console.error('could not fetch the token!');

‎tests/auth/oauth2/fixtures/keycloak/realm-export.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"clientId": "bruno",
1313
"enabled": true,
1414
"protocol": "openid-connect",
15-
"publicClient": false,
15+
"publicClient": true,
1616
"secret": "DSH25NOw5mMOCEIMrmm31EtUad4TbRLM",
1717
"standardFlowEnabled": true,
1818
"implicitFlowEnabled": true,
@@ -49,4 +49,4 @@
4949
]
5050
}
5151
]
52-
}
52+
}

‎tests/auth/oauth2/oauth2-state-validation.spec.ts‎

Lines changed: 43 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,26 @@ const clickGetAccessToken = async (page: Parameters<typeof openRequest>[0], requ
176176
await page.getByRole('button', { name: 'Get Access Token' }).click();
177177
};
178178

179+
/**
180+
* Common flow bootstrap shared by every test: restart the app, wait for a ready page,
181+
* stub `shell.openExternal`, install the callback capture, click "Get Access Token" for
182+
* the given request, and wait for the authorization URL to be captured.
183+
*/
184+
const startOAuth2Flow = async (
185+
restartApp: (options?: { initUserDataPath?: string }) => Promise<ElectronApplication>,
186+
requestName: string
187+
) => {
188+
const app = await restartApp();
189+
const page = await waitForReadyPage(app);
190+
191+
await stubOpenExternal(app); // fake opening the browser so we can read the login URL
192+
await installCallbackCapture(app);
193+
await clickGetAccessToken(page, requestName);
194+
await waitForAuthorizationStarted(app);
195+
196+
return { app, page };
197+
};
198+
179199
const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => {
180200
const url = new URL(callbackUrl);
181201
if (style === 'hash') {
@@ -197,13 +217,7 @@ test.describe('OAuth2 callback state validation', () => {
197217
test('authorization code: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => {
198218
test.setTimeout(60_000);
199219
const USER_STATE = 'brunoUserState';
200-
const app = await restartApp();
201-
const page = await waitForReadyPage(app);
202-
203-
await stubOpenExternal(app);
204-
await installCallbackCapture(app);
205-
await clickGetAccessToken(page, 'AuthCodeUserSuppliedState');
206-
await waitForAuthorizationStarted(app);
220+
const { app, page } = await startOAuth2Flow(restartApp, 'AuthCodeUserSuppliedState');
207221

208222
const authUrl = await getCapturedAuthUrl(app);
209223

@@ -236,19 +250,19 @@ test.describe('OAuth2 callback state validation', () => {
236250

237251
test('authorization code: (no state): issues a random state accepts matching callback', async ({ restartApp }) => {
238252
test.setTimeout(60_000);
239-
const app = await restartApp();
240-
const page = await waitForReadyPage(app);
241-
242-
await stubOpenExternal(app);
243-
await installCallbackCapture(app);
244-
await clickGetAccessToken(page, 'AuthorizationCode');
245-
await waitForAuthorizationStarted(app);
253+
const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode');
246254

247255
const authUrl = await getCapturedAuthUrl(app);
248256

249257
expect(authUrl).toBeTruthy();
250258

251-
const issuedState = await getIssuedState(app);
259+
const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => {
260+
const state = await getIssuedState(app);
261+
// No user state was configured, so Bruno must generate a random 32-char hex string
262+
// (crypto.randomBytes(16).toString('hex')).
263+
expect(state).toMatch(/^[0-9a-f]{32}$/);
264+
return state;
265+
});
252266

253267
const authCode = await test.step('obtain a valid auth code from Keycloak', () =>
254268
loginToKeycloakForAuthCode(authUrl as string));
@@ -270,15 +284,9 @@ test.describe('OAuth2 callback state validation', () => {
270284
});
271285

272286
test('authorization code: rejects callback when returned state does not match issued state', async ({ restartApp }) => {
273-
const app = await restartApp();
274-
const page = await waitForReadyPage(app);
275-
276-
await test.step('start the authorization code flow', async () => {
277-
await stubOpenExternal(app); // fake opening the browser so we can read the login URL
278-
await installCallbackCapture(app);
279-
await clickGetAccessToken(page, 'AuthorizationCode');
280-
await waitForAuthorizationStarted(app);
281-
});
287+
test.setTimeout(60_000);
288+
289+
const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode');
282290

283291
const issuedState = await getIssuedState(app);
284292

@@ -304,17 +312,8 @@ test.describe('OAuth2 callback state validation', () => {
304312

305313
test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => {
306314
test.setTimeout(60_000);
307-
308315
const USER_STATE = 'brunoUserState';
309-
const app = await restartApp();
310-
const page = await waitForReadyPage(app);
311-
312-
await test.step('start the implicit grant flow', async () => {
313-
await stubOpenExternal(app);
314-
await installCallbackCapture(app);
315-
await clickGetAccessToken(page, 'ImplicitUserSuppliedState');
316-
await waitForAuthorizationStarted(app);
317-
});
316+
const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState');
318317

319318
const issuedState = await test.step('capture and verify the issued state carries userState', async () => {
320319
const state = await getIssuedState(app);
@@ -341,17 +340,15 @@ test.describe('OAuth2 callback state validation', () => {
341340

342341
test('implicit grant: (no state): issues a random state accepts matching callback', async ({ restartApp }) => {
343342
test.setTimeout(60_000);
344-
const app = await restartApp();
345-
const page = await waitForReadyPage(app);
346-
347-
await test.step('start the implicit grant flow', async () => {
348-
await stubOpenExternal(app);
349-
await installCallbackCapture(app);
350-
await clickGetAccessToken(page, 'AuthorizationImplicit');
351-
await waitForAuthorizationStarted(app);
352-
});
343+
const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit');
353344

354-
const issuedState = await getIssuedState(app);
345+
const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => {
346+
const state = await getIssuedState(app);
347+
// No user state was configured, so Bruno must generate a random 32-char hex string
348+
// (crypto.randomBytes(16).toString('hex')).
349+
expect(state).toMatch(/^[0-9a-f]{32}$/);
350+
return state;
351+
});
355352

356353
const callbackUrl
357354
= `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`;
@@ -371,15 +368,8 @@ test.describe('OAuth2 callback state validation', () => {
371368
});
372369

373370
test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => {
374-
const app = await restartApp();
375-
const page = await waitForReadyPage(app);
376-
377-
await test.step('start the implicit grant flow', async () => {
378-
await stubOpenExternal(app);
379-
await installCallbackCapture(app);
380-
await clickGetAccessToken(page, 'AuthorizationImplicit');
381-
await waitForAuthorizationStarted(app);
382-
});
371+
test.setTimeout(60_000);
372+
const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit');
383373

384374
const issuedState = await test.step('capture the issued state', () => getIssuedState(app));
385375

0 commit comments

Comments
 (0)