diff --git a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml new file mode 100644 index 00000000000..c90af24c32b --- /dev/null +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -0,0 +1,32 @@ +name: 'Collect Keycloak Logs' +description: 'Stage and upload the Keycloak server logs from an OAuth2 e2e run (Linux, macOS, Windows)' + +inputs: + artifact-suffix: + description: 'Suffix for the uploaded log artifact name (linux, macos, windows)' + required: true + +runs: + using: 'composite' + steps: + - name: Stage Keycloak logs + shell: bash + run: | + set -euo pipefail + mkdir -p keycloak-logs + shopt -s nullglob + logs=("$RUNNER_TEMP"/keycloak*.log) + if (( ${#logs[@]} )); then + cp "${logs[@]}" keycloak-logs/ + else + # Keycloak is started by run-oauth2-e2e-tests, so a missing log usually means + # setup-keycloak failed first; that failure is the one worth surfacing. + echo "::warning::No Keycloak logs found in $RUNNER_TEMP." + fi + + - name: Upload Keycloak logs + uses: actions/upload-artifact@v4 + with: + name: keycloak-logs-oauth2-${{ inputs.artifact-suffix }} + path: keycloak-logs/ + retention-days: 30 diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml new file mode 100644 index 00000000000..1c742480b51 --- /dev/null +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -0,0 +1,76 @@ +name: 'Run OAuth2 E2E Tests' +description: 'Start Keycloak and run the OAuth2 (Keycloak) E2E tests on Linux, macOS and Windows' + +inputs: + artifact-suffix: + description: 'Suffix for the uploaded Playwright report artifact name (linux, macos, windows)' + required: true + +runs: + using: 'composite' + steps: + # Keycloak is started and the tests run in the same step because GitHub Actions kills + # background processes when a step ends. KC_HOME comes from the setup-keycloak step. + - name: Start Keycloak and run OAuth2 E2E tests + shell: bash + env: + KEYCLOAK_PORT: '8090' + run: | + set -euo pipefail + + if [ -z "${KC_HOME:-}" ]; then + echo "::error::KC_HOME is not set; setup-keycloak must run first" + exit 1 + fi + + if [ "${RUNNER_OS}" = "Windows" ]; then + kc_bin="${KC_HOME}/bin/kc.bat" + else + kc_bin="${KC_HOME}/bin/kc.sh" + fi + log="${RUNNER_TEMP}/keycloak.log" + + "${kc_bin}" start-dev --http-port="${KEYCLOAK_PORT}" --import-realm > "${log}" 2>&1 & + kc_pid=$! + # On Windows, kc_pid belongs to the kc.bat wrapper (cmd.exe), not to Java. + # `kill` would stop only the wrapper and leave Keycloak running, so use + # taskkill /T to kill the whole tree. + if [ "${RUNNER_OS}" = "Windows" ]; then + kc_winpid="$(cat "/proc/${kc_pid}/winpid")" + trap 'taskkill //PID "${kc_winpid}" //T //F > /dev/null 2>&1 || true' EXIT + else + trap 'kill "${kc_pid}" 2>/dev/null || true' EXIT + fi + + echo "Waiting for Keycloak (realm bruno) on :${KEYCLOAK_PORT} ..." + ready=false + for i in $(seq 1 60); do + if curl -fsS "http://127.0.0.1:${KEYCLOAK_PORT}/realms/bruno/.well-known/openid-configuration" > /dev/null 2>&1; then + ready=true + break + fi + sleep 2 + done + if [ "${ready}" != "true" ]; then + echo "::error::Keycloak did not become ready in time" + tail -n 100 "${log}" || true + exit 1 + fi + echo "Keycloak is ready." + + # Linux runners are headless, so Electron needs a virtual display. + if [ "${RUNNER_OS}" = "Linux" ]; then + xvfb-run npm run test:e2e:auth:oauth2 + else + npm run test:e2e:auth:oauth2 + fi + + - name: Upload Playwright Report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: playwright-report-oauth2-${{ inputs.artifact-suffix }} + path: | + playwright-report/ + test-results/ + retention-days: 30 diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml new file mode 100644 index 00000000000..98ade99ca23 --- /dev/null +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -0,0 +1,36 @@ +name: 'Setup Keycloak' +description: 'Provision Keycloak (download + realm import prep) for the OAuth2 e2e tests on Linux, macOS and Windows' + +inputs: + keycloak-version: + description: 'Keycloak release to download' + required: false + default: '26.3.3' + +runs: + using: 'composite' + steps: + - name: Setup Java 21 (Temurin) + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - name: Download and prepare Keycloak + shell: bash + working-directory: ${{ runner.temp }} + env: + KEYCLOAK_VERSION: ${{ inputs.keycloak-version }} + run: | + set -euo pipefail + + curl -fsSL -o keycloak.tar.gz \ + "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.tar.gz" + tar -xzf keycloak.tar.gz + KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" + + mkdir -p "${KC_HOME}/data/import" + cp "${GITHUB_WORKSPACE}/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json" \ + "${KC_HOME}/data/import/realm-export.json" + + echo "KC_HOME=${KC_HOME}" >> "${GITHUB_ENV}" + echo "Keycloak prepared at ${KC_HOME}" diff --git a/.github/workflows/tests-linux.yml b/.github/workflows/tests-linux.yml index 47c6e0dea12..21c1f42b30f 100644 --- a/.github/workflows/tests-linux.yml +++ b/.github/workflows/tests-linux.yml @@ -230,4 +230,34 @@ jobs: uses: ./.github/actions/auth/oauth1/linux/start-test-server - name: Run OAuth1 CLI Tests - uses: ./.github/actions/auth/oauth1/linux/run-oauth1-cli-tests \ No newline at end of file + uses: ./.github/actions/auth/oauth1/linux/run-oauth1-cli-tests + + oauth2-tests: + name: OAuth 2.0 Auth Tests (Linux) + timeout-minutes: 60 + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + + - name: Setup Node Dependencies + uses: ./.github/actions/common/setup-node-deps + + - name: Setup Feature Dependencies + uses: ./.github/actions/auth/oauth1/linux/setup-feature-specific-deps + + - name: Setup Keycloak + uses: ./.github/actions/auth/oauth2/setup-keycloak + + - name: Run OAuth2 E2E Tests + uses: ./.github/actions/auth/oauth2/run-oauth2-e2e-tests + with: + artifact-suffix: linux + + # Runs even when setup-keycloak or the test step failed, so a broken IdP is debuggable. + - name: Collect Keycloak Logs + if: ${{ !cancelled() }} + uses: ./.github/actions/auth/oauth2/collect-keycloak-logs + with: + artifact-suffix: linux diff --git a/.github/workflows/tests-macos.yml b/.github/workflows/tests-macos.yml index 55055b83472..95f230d2d9e 100644 --- a/.github/workflows/tests-macos.yml +++ b/.github/workflows/tests-macos.yml @@ -162,4 +162,31 @@ jobs: uses: ./.github/actions/auth/oauth1/macos/start-test-server - name: Run OAuth1 CLI Tests - uses: ./.github/actions/auth/oauth1/macos/run-oauth1-cli-tests \ No newline at end of file + uses: ./.github/actions/auth/oauth1/macos/run-oauth1-cli-tests + + oauth2-tests: + name: OAuth 2.0 Auth Tests (macOS) + timeout-minutes: 60 + runs-on: macos-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + + - name: Setup Node Dependencies + uses: ./.github/actions/common/setup-node-deps + + - name: Setup Keycloak + uses: ./.github/actions/auth/oauth2/setup-keycloak + + - name: Run OAuth2 E2E Tests + uses: ./.github/actions/auth/oauth2/run-oauth2-e2e-tests + with: + artifact-suffix: macos + + # Runs even when setup-keycloak or the test step failed, so a broken IdP is debuggable. + - name: Collect Keycloak Logs + if: ${{ !cancelled() }} + uses: ./.github/actions/auth/oauth2/collect-keycloak-logs + with: + artifact-suffix: macos diff --git a/.github/workflows/tests-windows.yml b/.github/workflows/tests-windows.yml index 8903b6d04b7..68560aa6239 100644 --- a/.github/workflows/tests-windows.yml +++ b/.github/workflows/tests-windows.yml @@ -175,3 +175,30 @@ jobs: - name: Run OAuth1 CLI Tests uses: ./.github/actions/auth/oauth1/windows/run-oauth1-cli-tests + + oauth2-tests: + name: OAuth 2.0 Auth Tests (Windows) + timeout-minutes: 60 + runs-on: windows-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + + - name: Setup Node Dependencies + uses: ./.github/actions/common/setup-node-deps + + - name: Setup Keycloak + uses: ./.github/actions/auth/oauth2/setup-keycloak + + - name: Run OAuth2 E2E Tests + uses: ./.github/actions/auth/oauth2/run-oauth2-e2e-tests + with: + artifact-suffix: windows + + # Runs even when setup-keycloak or the test step failed, so a broken IdP is debuggable. + - name: Collect Keycloak Logs + if: ${{ !cancelled() }} + uses: ./.github/actions/auth/oauth2/collect-keycloak-logs + with: + artifact-suffix: windows diff --git a/.gitignore b/.gitignore index 49c1926d108..bad6f3fba2e 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,7 @@ yarn-error.log* /test-results/ /playwright-report/ /playwright/.cache/ +/keycloak-logs/ #dev editor bruno.iml diff --git a/docs/playwright-testing-guide.md b/docs/playwright-testing-guide.md index be3c26ff77a..acc9299d66d 100644 --- a/docs/playwright-testing-guide.md +++ b/docs/playwright-testing-guide.md @@ -196,6 +196,13 @@ npx playwright test e2e/tests/common/home-screen.spec.ts npx playwright test e2e/tests/folder-a/ ``` +### Projects That Need External Services + +Most projects run self-contained. Two need a service started by hand first; each suite's readme has the steps: + +- `oauth2` (`npm run test:e2e:auth:oauth2`) — a local Keycloak instance, see [`tests/auth/oauth2/README.md`](../tests/auth/oauth2/README.md) +- `ssl` (`npm run test:e2e:ssl`) — generated certificates and a local HTTPS server, see [`tests/ssl/custom-ca-certs/server/readme.md`](../tests/ssl/custom-ca-certs/server/readme.md) + ### Advanced Options ```bash diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index 3af3336ae30..961c6d564c5 100644 --- a/e2e/pages/request/auth.ts +++ b/e2e/pages/request/auth.ts @@ -32,7 +32,9 @@ export const buildAuthLocators = (page: Page) => ({ signatureMethodDropdown: () => page.getByTestId('oauth1-signature-method-dropdown'), signatureMethodMenu: () => page.getByTestId('oauth1-signature-method-dropdown-dropdown'), placementDropdown: () => page.getByTestId('oauth1-placement-dropdown'), - placementMenu: () => page.getByTestId('oauth1-placement-dropdown-dropdown') + placementMenu: () => page.getByTestId('oauth1-placement-dropdown-dropdown'), + placementSelector: () => page.getByTestId('auth-placement-selector'), + placementLabel: () => page.getByTestId('auth-placement-label') }, oauth2: { grantTypeDropdown: () => page.getByTestId('grant-type-dropdown'), @@ -46,7 +48,10 @@ export const buildAuthLocators = (page: Page) => ({ getAccessTokenButton: () => page.getByRole('button', { name: 'Get Access Token' }), clearCacheButton: () => page.getByRole('button', { name: 'Clear Cache' }), tokenSection: (title: string) => page.getByRole('heading', { name: title, exact: true }), - copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }) + copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }), + noToken: () => page.getByTestId('oauth2-no-token'), + tokenValue: (tokenKey: 'access-token' | 'refresh-token' | 'id-token') => page.getByTestId(`oauth2-token-value-${tokenKey}`), + getAccessTokenBtn: () => page.getByTestId('oauth2-get-access-token') }, modeSelector: () => page.getByTestId('auth-mode-selector'), modeLabel: () => page.getByTestId('auth-mode-label'), diff --git a/e2e/tests/auth/oauth2/README.md b/e2e/tests/auth/oauth2/README.md new file mode 100644 index 00000000000..25e269ca2c9 --- /dev/null +++ b/e2e/tests/auth/oauth2/README.md @@ -0,0 +1,34 @@ +# OAuth2 e2e tests + +The `oauth2` Playwright project drives real OAuth2 flows against a local Keycloak instance, +so Keycloak must be running before the specs start. + +## What the specs expect + +- Keycloak reachable at `http://127.0.0.1:8090` +- The `bruno` realm imported from `fixtures/keycloak/realm-export.json` + +CI provisions this through `.github/actions/auth/oauth2/setup-keycloak` and +`.github/actions/auth/oauth2/run-oauth2-e2e-tests`; keep the local setup below in step with them. + +## Running locally + +Start Keycloak with the fixture realm imported: + +```bash +docker run -d --name bruno-keycloak -p 8090:8080 \ + -v "$PWD/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ + quay.io/keycloak/keycloak:26.3.3 start-dev --http-port=8080 --import-realm +``` + +Wait until `http://127.0.0.1:8090/realms/bruno` responds, then run the suite: + +```bash +npm run test:e2e:auth:oauth2 +``` + +Stop and remove the container when you are done: + +```bash +docker rm -f bruno-keycloak +``` diff --git a/e2e/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml new file mode 100644 index 00000000000..518864b2def --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml @@ -0,0 +1,37 @@ +info: + name: AuthCodeUserSuppliedState + type: http + seq: 3 + +http: + method: GET + url: "{{userinfo_url}}" + auth: + type: oauth2 + flow: authorization_code + authorizationUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/auth" + accessTokenUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/token" + callbackUrl: bruno://app/oauth2/callback + credentials: + clientId: bruno + clientSecret: "{{client_secret}}" + placement: body + scope: openid + state: brunoUserState + pkce: + disabled: true + tokenConfig: + id: credentials + placement: + header: Bearer + source: access_token + settings: + autoFetchToken: true + autoRefreshToken: false + +settings: + encodeUrl: true + timeout: 0 + followRedirects: true + maxRedirects: 5 + forwardAuthorizationHeader: true diff --git a/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml new file mode 100644 index 00000000000..b6b000a45d9 --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml @@ -0,0 +1,36 @@ +info: + name: AuthorizationCode + type: http + seq: 1 + +http: + method: GET + url: "{{userinfo_url}}" + auth: + type: oauth2 + flow: authorization_code + authorizationUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/auth" + accessTokenUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/token" + callbackUrl: bruno://app/oauth2/callback + credentials: + clientId: bruno + clientSecret: "{{client_secret}}" + placement: body + scope: openid + pkce: + disabled: true + tokenConfig: + id: credentials + placement: + header: Bearer + source: access_token + settings: + autoFetchToken: true + autoRefreshToken: false + +settings: + encodeUrl: true + timeout: 0 + followRedirects: true + maxRedirects: 5 + forwardAuthorizationHeader: true diff --git a/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml new file mode 100644 index 00000000000..58285711612 --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml @@ -0,0 +1,30 @@ +info: + name: AuthorizationImplicit + type: http + seq: 2 + +http: + method: GET + url: "{{userinfo_url}}" + auth: + type: oauth2 + flow: implicit + authorizationUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/auth" + callbackUrl: bruno://app/oauth2/callback + credentials: + clientId: bruno + scope: openid + tokenConfig: + id: credentials + placement: + header: Bearer + source: access_token + settings: + autoFetchToken: true + +settings: + encodeUrl: true + timeout: 0 + followRedirects: true + maxRedirects: 5 + forwardAuthorizationHeader: true diff --git a/e2e/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml b/e2e/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml new file mode 100644 index 00000000000..72b7490ca9e --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml @@ -0,0 +1,31 @@ +info: + name: ImplicitUserSuppliedState + type: http + seq: 4 + +http: + method: GET + url: "{{userinfo_url}}" + auth: + type: oauth2 + flow: implicit + authorizationUrl: "{{host}}/realms/{{realm}}/protocol/openid-connect/auth" + callbackUrl: bruno://app/oauth2/callback + credentials: + clientId: bruno + scope: openid + state: brunoUserState + tokenConfig: + id: credentials + placement: + header: Bearer + source: access_token + settings: + autoFetchToken: true + +settings: + encodeUrl: true + timeout: 0 + followRedirects: true + maxRedirects: 5 + forwardAuthorizationHeader: true diff --git a/e2e/tests/auth/oauth2/fixtures/collection/bruno.json b/e2e/tests/auth/oauth2/fixtures/collection/bruno.json new file mode 100644 index 00000000000..c2925567f67 --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/bruno.json @@ -0,0 +1,5 @@ +{ + "version": "1", + "name": "oauth2-state", + "type": "collection" +} diff --git a/e2e/tests/auth/oauth2/fixtures/collection/environments/Local.yml b/e2e/tests/auth/oauth2/fixtures/collection/environments/Local.yml new file mode 100644 index 00000000000..03c7059f42f --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/environments/Local.yml @@ -0,0 +1,9 @@ +variables: + - name: host + value: http://127.0.0.1:8090 + - name: realm + value: bruno + - name: client_secret + value: DSH25NOw5mMOCEIMrmm31EtUad4TbRLM + - name: userinfo_url + value: http://127.0.0.1:8090/realms/bruno/protocol/openid-connect/userinfo diff --git a/e2e/tests/auth/oauth2/fixtures/collection/opencollection.yml b/e2e/tests/auth/oauth2/fixtures/collection/opencollection.yml new file mode 100644 index 00000000000..b8e7893c705 --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/collection/opencollection.yml @@ -0,0 +1,3 @@ +opencollection: "1.0.0" +info: + name: oauth2-state diff --git a/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json b/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json new file mode 100644 index 00000000000..e14d0b39ed4 --- /dev/null +++ b/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json @@ -0,0 +1,53 @@ +{ + "realm": "bruno", + "enabled": true, + "sslRequired": "none", + "registrationAllowed": false, + "loginWithEmailAllowed": true, + "duplicateEmailsAllowed": false, + "resetPasswordAllowed": false, + "editUsernameAllowed": false, + "clients": [ + { + "clientId": "bruno", + "enabled": true, + "protocol": "openid-connect", + "publicClient": false, + "clientAuthenticatorType": "client-secret", + "secret": "DSH25NOw5mMOCEIMrmm31EtUad4TbRLM", + "standardFlowEnabled": true, + "implicitFlowEnabled": true, + "directAccessGrantsEnabled": true, + "serviceAccountsEnabled": false, + "fullScopeAllowed": true, + "redirectUris": [ + "bruno://app/oauth2/callback", + "bruno://app/oauth2/callback/*" + ], + "webOrigins": [ + "*" + ], + "attributes": { + "post.logout.redirect.uris": "+" + } + } + ], + "users": [ + { + "username": "testuser", + "enabled": true, + "emailVerified": true, + "email": "testuser@example.com", + "firstName": "Test", + "lastName": "User", + "requiredActions": [], + "credentials": [ + { + "type": "password", + "value": "testpassword", + "temporary": false + } + ] + } + ] +} diff --git a/e2e/tests/auth/oauth2/helpers.ts b/e2e/tests/auth/oauth2/helpers.ts new file mode 100644 index 00000000000..e8f5d308f82 --- /dev/null +++ b/e2e/tests/auth/oauth2/helpers.ts @@ -0,0 +1,137 @@ +import type { ElectronApplication } from 'playwright'; +import { test, expect, waitForReadyPage } from '../../../playwright'; +import { openRequest, selectRequestPaneTab, selectEnvironment, buildCommonLocators } from '../../../pages'; + +const COLLECTION = 'oauth2-state'; +const KEYCLOAK_USER = 'testuser'; +const KEYCLOAK_PASSWORD = 'testpassword'; + +const loginFormActionRegex = /action="([^"]+login-actions\/authenticate[^"]*)"/; + +// This block stubs Electron's shell.openExternal inside the Bruno app so the OAuth2 test +// can intercept the authorization URL instead of opening a real browser. +export const stubOpenExternal = (app: ElectronApplication) => + app.evaluate(({ shell }) => { + (globalThis as any).__brunoCapturedAuthUrl = null; + shell.openExternal = async (url: string) => { + (globalThis as any).__brunoCapturedAuthUrl = url; + }; + }); + +export const clickGetAccessToken = async (page: Parameters[0], requestName: string) => { + await openRequest(page, COLLECTION, requestName); + await selectEnvironment(page, 'Local', 'collection'); + await selectRequestPaneTab(page, 'Auth'); + await buildCommonLocators(page).auth.oauth2.getAccessTokenBtn().click(); +}; + +export const getCapturedAuthUrl = (app: ElectronApplication): Promise => + app.evaluate(() => (globalThis as any).__brunoCapturedAuthUrl ?? null); + +export const waitForAuthorizationStarted = async (app: ElectronApplication) => { + await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); +}; + +export const startOAuth2Flow = async ( + restartApp: (options?: { initUserDataPath?: string }) => Promise, + requestName: string +) => { + const app = await restartApp(); + const page = await waitForReadyPage(app); + + // Fake opening the browser so we can read the login URL. + await stubOpenExternal(app); + + await clickGetAccessToken(page, requestName); + await waitForAuthorizationStarted(app); + + return { app, page }; +}; + +/** `state` Bruno sent on the authorization URL (stored internally as expectedState). */ +export const getIssuedStateFromAuthorizationUrl = async (app: ElectronApplication): Promise => { + const authUrl = await getCapturedAuthUrl(app); + expect(authUrl, 'authorization URL should have been opened').toBeTruthy(); + const state = new URL(authUrl as string).searchParams.get('state'); + expect(state, 'issued state should be present on the authorization URL').toBeTruthy(); + return state as string; +}; + +/** + * Log in to Keycloak as the test user and return the callback URL it redirects to. + * For the authorization code flow the code is in the query; for the implicit flow + * the token is in the fragment. + */ +export const loginToKeycloak = async (authorizationUrl: string): Promise => { + const loginPage = await fetch(authorizationUrl, { redirect: 'manual' }); + expect(loginPage.ok, 'Keycloak authorize should return a login page').toBeTruthy(); + + const cookies = ((loginPage.headers as Headers & { getSetCookie?: () => string[] }).getSetCookie?.() ?? []) + .map((c) => c.split(';')[0]) + .join('; '); + + const html = await loginPage.text(); + + // Extract the login form's action URL; it carries per-request session params, so it can't be hardcoded. + const formActionMatch = html.match(loginFormActionRegex); + expect(formActionMatch, 'Keycloak login page should expose a form action').toBeTruthy(); + + // HTML escapes & as & inside attributes; restore it so the query params reach Keycloak intact. + const formAction = formActionMatch![1].replace(/&/g, '&'); + const submission = await fetch(formAction, { + method: 'POST', + redirect: 'manual', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + ...(cookies ? { cookie: cookies } : {}) + }, + body: new URLSearchParams({ + username: KEYCLOAK_USER, + password: KEYCLOAK_PASSWORD, + credentialId: '' + }).toString() + }); + + const location = submission.headers.get('location'); + expect(location, 'Keycloak login should redirect to the callback URL').toBeTruthy(); + return location as string; +}; + +export const getAuthCodeFromCallbackUrl = (callbackUrl: string): string => { + const code = new URL(callbackUrl).searchParams.get('code'); + expect(code, 'Keycloak callback redirect should carry an auth code').toBeTruthy(); + return code as string; +}; + +export const getAccessTokenFromCallbackUrl = (callbackUrl: string): string => { + const token = new URLSearchParams(new URL(callbackUrl).hash.slice(1)).get('access_token'); + expect(token, 'Keycloak callback redirect should carry an access token in the fragment').toBeTruthy(); + return token as string; +}; + +/** Fire a deep-link callback through the real protocol handler (cross-platform path). */ +export const fireDeepLinkCallback = (app: ElectronApplication, url: string) => + app.evaluate(({ app: electronApp }, callbackUrl) => { + electronApp.emit('second-instance', {}, [callbackUrl]); + }, url); + +/** Expand the Access Token section of the token viewer and return the stored token. */ +export const readFetchedAccessToken = async (page: Parameters[0]) => { + const { tokenSection, tokenValue } = buildCommonLocators(page).auth.oauth2; + await expect(tokenSection('Access Token')).toBeVisible({ timeout: 15_000 }); + await tokenSection('Access Token').click(); + return tokenValue('access-token').textContent(); +}; + +const STATE_MISMATCH_ERROR + = 'OAuth2 state mismatch: the returned state does not match the issued state.'; + +// The rejection must happen before any token exchange, so once the error is +// visible the flow has settled and the absence of a token is final. +export const expectStateMismatchWithoutToken = async (page: Parameters[0]) => { + const locators = buildCommonLocators(page); + await test.step('surface a state mismatch error and no token', async () => { + await expect(locators.response.pane().getByText(STATE_MISMATCH_ERROR)).toBeVisible({ timeout: 15_000 }); + await expect(locators.auth.oauth2.noToken()).toBeVisible(); + }); +}; diff --git a/e2e/tests/auth/oauth2/init-user-data/preferences.json b/e2e/tests/auth/oauth2/init-user-data/preferences.json new file mode 100644 index 00000000000..ed131810837 --- /dev/null +++ b/e2e/tests/auth/oauth2/init-user-data/preferences.json @@ -0,0 +1,11 @@ +{ + "maximized": false, + "lastOpenedCollections": ["{{collectionPath}}"], + "preferences": { + "request": { + "oauth2": { + "useSystemBrowser": true + } + } + } +} diff --git a/e2e/tests/auth/oauth2/oauth2-state-validation.spec.ts b/e2e/tests/auth/oauth2/oauth2-state-validation.spec.ts new file mode 100644 index 00000000000..ac1e46e58d5 --- /dev/null +++ b/e2e/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -0,0 +1,142 @@ +// Requires a local Keycloak instance; see ./README.md for setup. + +import { test, expect } from '../../../playwright'; +import { + startOAuth2Flow, + getCapturedAuthUrl, + getIssuedStateFromAuthorizationUrl, + loginToKeycloak, + getAuthCodeFromCallbackUrl, + getAccessTokenFromCallbackUrl, + fireDeepLinkCallback, + readFetchedAccessToken, + expectStateMismatchWithoutToken +} from './helpers'; + +const KEYCLOAK_BASE_URL = 'http://127.0.0.1:8090'; +const KEYCLOAK_REALM = 'bruno'; +const CALLBACK_URL = 'bruno://app/oauth2/callback'; +const PROVIDER_AUTH_CODE = 'provider-auth-code'; +const PROVIDER_ACCESS_TOKEN = 'provider-access-token'; +const WRONG_STATE = 'not-the-issued-state'; +const USER_STATE = 'brunoUserState'; +// Bruno issues crypto.randomBytes(16).toString('hex') when no user state is configured. +const GENERATED_STATE_PATTERN = /^[0-9a-f]{32}$/; + +test.beforeAll(async () => { + const response = await fetch(`${KEYCLOAK_BASE_URL}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`); + expect( + response.ok, + `Keycloak realm "${KEYCLOAK_REALM}" should be reachable at ${KEYCLOAK_BASE_URL}` + ).toBeTruthy(); +}); + +test.describe('OAuth2 callback state validation', () => { + // Each test restarts the app and does a real Keycloak login, so allow more than the 30s default. + test.describe.configure({ timeout: 60_000 }); + + test('authorization code: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'AuthCodeUserSuppliedState'); + + const authUrl = await getCapturedAuthUrl(app); + + expect(authUrl).toBeTruthy(); + + const issuedState = await test.step('capture and verify the issued state carries userState', async () => { + const state = await getIssuedStateFromAuthorizationUrl(app); + expect(state).toBe(USER_STATE); + return state; + }); + + const authCode = await test.step('obtain a valid auth code from Keycloak', async () => + getAuthCodeFromCallbackUrl(await loginToKeycloak(authUrl as string))); + + const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + + await fireDeepLinkCallback(app, callbackUrl); + + expect(await readFetchedAccessToken(page)).toBeTruthy(); + }); + + test('authorization code: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode'); + + const authUrl = await getCapturedAuthUrl(app); + + expect(authUrl).toBeTruthy(); + + const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => { + const state = await getIssuedStateFromAuthorizationUrl(app); + expect(state).toMatch(GENERATED_STATE_PATTERN); + return state; + }); + + const authCode = await test.step('obtain a valid auth code from Keycloak', async () => + getAuthCodeFromCallbackUrl(await loginToKeycloak(authUrl as string))); + + const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + + await fireDeepLinkCallback(app, callbackUrl); + + expect(await readFetchedAccessToken(page)).toBeTruthy(); + }); + + test('authorization code: rejects callback when returned state does not match issued state', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode'); + + const callbackUrl = `${CALLBACK_URL}?code=${PROVIDER_AUTH_CODE}&state=${WRONG_STATE}`; + await fireDeepLinkCallback(app, callbackUrl); + + await expectStateMismatchWithoutToken(page); + }); + + test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState'); + + const authUrl = await getCapturedAuthUrl(app); + + expect(authUrl).toBeTruthy(); + + await test.step('capture and verify the issued state carries userState', async () => { + const state = await getIssuedStateFromAuthorizationUrl(app); + expect(state).toBe(USER_STATE); + }); + + const callbackUrl = await test.step('obtain a token callback from Keycloak', () => + loginToKeycloak(authUrl as string)); + + await fireDeepLinkCallback(app, callbackUrl); + + expect(await readFetchedAccessToken(page)).toBe(getAccessTokenFromCallbackUrl(callbackUrl)); + }); + + test('implicit grant: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); + + const authUrl = await getCapturedAuthUrl(app); + + expect(authUrl).toBeTruthy(); + + await test.step('capture and verify a cryptographically random state was issued', async () => { + const state = await getIssuedStateFromAuthorizationUrl(app); + expect(state).toMatch(GENERATED_STATE_PATTERN); + }); + + const callbackUrl = await test.step('obtain a token callback from Keycloak', () => + loginToKeycloak(authUrl as string)); + + await fireDeepLinkCallback(app, callbackUrl); + + expect(await readFetchedAccessToken(page)).toBe(getAccessTokenFromCallbackUrl(callbackUrl)); + }); + + test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => { + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); + + const callbackUrl = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&state=${WRONG_STATE}`; + + await fireDeepLinkCallback(app, callbackUrl); + + await expectStateMismatchWithoutToken(page); + }); +}); diff --git a/package.json b/package.json index dfe09c8d436..fd6c84fd9c6 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "test:e2e:ssl": "playwright test --project=ssl", "test:e2e:auth": "playwright test --project=auth", "test:e2e:mock-server": "playwright test --project=mock-server", + "test:e2e:auth:oauth2": "playwright test --project=oauth2", "test:e2e:sanity": "playwright test --project=default --project=system-pac --grep @sanity", "test:benchmark": "playwright test --config=playwright.benchmark.config.ts", "lint": "cross-env NODE_OPTIONS=\"--max_old_space_size=4096\" npx eslint", 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 d372ecb06dc..c1a19b2ec7e 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 @@ -164,6 +164,7 @@ const Oauth2ActionButtons = ({ item, request, collection, url: accessTokenUrl, c onClick={handleFetchOauth2Credentials} disabled={fetchingToken || refreshingToken} loading={fetchingToken} + data-testid="oauth2-get-access-token" > Get Access Token diff --git a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2TokenViewer/index.js b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2TokenViewer/index.js index 2aa41329515..02dd0ee8f52 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2TokenViewer/index.js +++ b/packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2TokenViewer/index.js @@ -5,7 +5,7 @@ import { IconChevronDown, IconChevronRight, IconCopy, IconCheck } from '@tabler/ import { getAllVariables } from 'utils/collections/index'; import { interpolate } from '@usebruno/common'; -const TokenSection = ({ title, token }) => { +const TokenSection = ({ title, token, testId }) => { if (!token) return null; const [isExpanded, setIsExpanded] = useState(false); @@ -62,7 +62,7 @@ const TokenSection = ({ title, token }) => { : } -
+
{token}
@@ -140,9 +140,9 @@ const Oauth2TokenViewer = ({ collection, item, url, credentialsId, handleRun })
Error fetching token. Check network logs for more details.
) : (
- - - + + + {(creds.token_type || creds.scope) ? (
@@ -166,7 +166,7 @@ const Oauth2TokenViewer = ({ collection, item, url, credentialsId, handleRun })
) ) : ( -
No token found
+
No token found
)} ); diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index ddef799f8b6..84274a7510e 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -308,9 +308,8 @@ 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. + // 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 }); const authorizationUrlWithQueryParams = new URL(authorizationUrl); @@ -713,8 +712,8 @@ const generateCodeVerifier = () => { }; // 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. +// A user-supplied state is trimmed and used if anything remains; a missing or +// whitespace-only state falls back to a cryptographically random value. const generateState = ({ userState }) => { const trimmedUserState = userState?.trim(); if (trimmedUserState && trimmedUserState.length > 0) { diff --git a/playwright.config.ts b/playwright.config.ts index 3d8bd245e34..a27b9e18e49 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -33,7 +33,12 @@ export default defineConfig({ }, { name: 'auth', - testDir: './e2e/tests/auth' + testDir: './e2e/tests/auth', + testIgnore: ['oauth2/**'] // oauth2 specs run in their own project (needs a Keycloak IdP) + }, + { + name: 'oauth2', + testDir: './e2e/tests/auth/oauth2' }, { name: 'ssl',