From cc1c7975027d4ab860d270932446e935280854af Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 11 Sep 2026 13:43:59 +0530 Subject: [PATCH 01/25] feat(oauth2): add Keycloak-backed OAuth2 e2e tests and CI setup Test the OAuth 2.0 authorization code and implicit flows against a real identity provider on Linux, macOS and Windows instead of a mock server. Tests - Add OAuth2 state-validation e2e specs with a Keycloak fixture realm covering user-supplied state, generated random state and callback state-mismatch rejection for both grants. - Fix OAuth2 state handling and error messaging in the app and electron layers, and remove the unused clearOauth2Error helper. CI - Add three shared composite actions under .github/actions/auth/oauth2: setup-keycloak (Java 21 + download and prepare the Keycloak zip), run-oauth2-e2e-tests (start Keycloak, wait, run the suite, stop it) and collect-keycloak-logs (stage the server log from RUNNER_TEMP and upload). - Use bash on every OS so one script covers Linux, macOS and Windows; the only OS switch is kc.sh vs kc.bat. Keycloak is started in the test step because Windows kills a step's process tree when the step ends. - Extract with tar instead of unzip, which is present on all three runner images. Keep all Keycloak files in RUNNER_TEMP. - Upload test-results/ alongside playwright-report/ so traces are kept, collect Keycloak logs under if: !cancelled(), and narrow the oauth2 jobs to contents: read. --- .../oauth2/collect-keycloak-logs/action.yml | 33 ++ .../oauth2/run-oauth2-e2e-tests/action.yml | 79 ++++ .../auth/oauth2/setup-keycloak/action.yml | 42 +++ .github/workflows/tests-linux.yml | 33 +- .github/workflows/tests-macos.yml | 29 +- .github/workflows/tests-windows.yml | 27 ++ .gitignore | 1 + package.json | 1 + .../Auth/OAuth2/Oauth2ActionButtons/index.js | 2 +- packages/bruno-electron/src/utils/oauth2.js | 4 +- playwright.config.ts | 7 +- .../collection/AuthCodeUserSuppliedState.bru | 31 ++ .../fixtures/collection/AuthorizationCode.bru | 31 ++ .../collection/AuthorizationImplicit.bru | 25 ++ .../collection/ImplicitUserSuppliedState.bru | 25 ++ .../oauth2/fixtures/collection/bruno.json | 5 + .../collection/environments/Local.bru | 6 + .../fixtures/keycloak/realm-export.json | 53 +++ .../oauth2/init-user-data/preferences.json | 11 + .../oauth2/oauth2-state-validation.spec.ts | 351 ++++++++++++++++++ 20 files changed, 790 insertions(+), 6 deletions(-) create mode 100644 .github/actions/auth/oauth2/collect-keycloak-logs/action.yml create mode 100644 .github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml create mode 100644 .github/actions/auth/oauth2/setup-keycloak/action.yml create mode 100644 tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru create mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru create mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru create mode 100644 tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru create mode 100644 tests/auth/oauth2/fixtures/collection/bruno.json create mode 100644 tests/auth/oauth2/fixtures/collection/environments/Local.bru create mode 100644 tests/auth/oauth2/fixtures/keycloak/realm-export.json create mode 100644 tests/auth/oauth2/init-user-data/preferences.json create mode 100644 tests/auth/oauth2/oauth2-state-validation.spec.ts 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..c4efad85dd0 --- /dev/null +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -0,0 +1,33 @@ +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: + # Keycloak logs live in RUNNER_TEMP (outside the workspace), so stage them into the + # workspace where upload-artifact can pick them up. bash is available on all three runner + # OSes (Git Bash on Windows), so one script covers them all. + - name: Stage Keycloak logs + shell: bash + run: | + set -uo pipefail + mkdir -p keycloak-logs + shopt -s nullglob + logs=("$RUNNER_TEMP"/keycloak*.log) + if (( ${#logs[@]} )); then + cp "${logs[@]}" keycloak-logs/ + else + echo "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..f8ab774cdcd --- /dev/null +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -0,0 +1,79 @@ +name: 'Run OAuth2 E2E Tests' +description: 'Start Keycloak and run the OAuth2 (Keycloak) E2E tests on Linux, macOS and Windows' + +inputs: + use-xvfb: + description: 'Wrap the test run in xvfb-run (needed on headless Linux)' + required: false + default: 'false' + port: + description: 'HTTP port Keycloak listens on' + required: false + default: '8090' + artifact-suffix: + description: 'Suffix for the uploaded Playwright report artifact name (linux, macos, windows)' + required: true + +runs: + using: 'composite' + steps: + # Keycloak is started HERE — in the same step as the tests — on purpose. On Windows, + # GitHub Actions kills a step's child-process tree when the step ends (Job Object), so a + # server started in an earlier step is dead by the time tests run. Doing the same on every + # OS keeps a single script. KC_HOME comes from the setup-keycloak step. bash is available + # on all three runner OSes (Git Bash on Windows); kc.bat vs kc.sh is the only OS switch. + - name: Start Keycloak and run OAuth2 E2E tests + shell: bash + env: + USE_XVFB: ${{ inputs.use-xvfb }} + KEYCLOAK_PORT: ${{ inputs.port }} + 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=$! + trap 'kill "${kc_pid}" 2>/dev/null || true' EXIT + + 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." + + if [ "${USE_XVFB}" = "true" ]; 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..2b09435a8bd --- /dev/null +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -0,0 +1,42 @@ +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' + + # NOTE: Keycloak is intentionally NOT started here. On Windows, GitHub Actions runs each + # step inside a Job Object that terminates the step's entire child-process tree when the + # step completes — so a server started in this step would be killed before the test step + # runs. It is downloaded/prepared here and started in the shared step that runs the tests + # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three + # runner OSes (Git Bash on Windows); tar extracts zips everywhere, unlike unzip. + - name: Download and prepare Keycloak + shell: bash + env: + KEYCLOAK_VERSION: ${{ inputs.keycloak-version }} + run: | + set -euo pipefail + + curl -fsSL -o "${RUNNER_TEMP}/keycloak.zip" \ + "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.zip" + tar -xf "${RUNNER_TEMP}/keycloak.zip" -C "${RUNNER_TEMP}" + KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" + + mkdir -p "${KC_HOME}/data/import" + cp "${GITHUB_WORKSPACE}/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..df0b464aec7 100644 --- a/.github/workflows/tests-linux.yml +++ b/.github/workflows/tests-linux.yml @@ -230,4 +230,35 @@ 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: + use-xvfb: 'true' + 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 \ No newline at end of file diff --git a/.github/workflows/tests-macos.yml b/.github/workflows/tests-macos.yml index 55055b83472..f60f159230f 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 \ No newline at end of file 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/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..6e57463ccf2 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,7 @@ 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 { responseReceived, responseCleared } from 'providers/ReduxStore/slices/collections'; import { updateResponsePaneTab } from 'providers/ReduxStore/slices/tabs'; import { getAllVariables } from 'utils/collections/index'; import { formatIpcError } from 'utils/common/error'; diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index ddef799f8b6..a627853e75c 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -713,8 +713,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. +// If the user supplies a non-empty state, it is used as-is; otherwise a +// cryptographically random value is generated. 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', diff --git a/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru b/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru new file mode 100644 index 00000000000..daad1468144 --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru @@ -0,0 +1,31 @@ +meta { + name: AuthCodeUserSuppliedState + type: http + seq: 3 +} + +get { + url: {{userinfo_url}} + body: none + auth: oauth2 +} + +auth:oauth2 { + grant_type: authorization_code + callback_url: bruno://app/oauth2/callback + authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth + access_token_url: {{host}}/realms/{{realm}}/protocol/openid-connect/token + refresh_token_url: + client_id: bruno + client_secret: {{client_secret}} + scope: openid + state: brunoUserState + pkce: false + credentials_placement: body + credentials_id: credentials + token_source: access_token + token_placement: header + token_header_prefix: Bearer + auto_fetch_token: true + auto_refresh_token: false +} diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru b/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru new file mode 100644 index 00000000000..5aeb75acf0e --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru @@ -0,0 +1,31 @@ +meta { + name: AuthorizationCode + type: http + seq: 1 +} + +get { + url: {{userinfo_url}} + body: none + auth: oauth2 +} + +auth:oauth2 { + grant_type: authorization_code + callback_url: bruno://app/oauth2/callback + authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth + access_token_url: {{host}}/realms/{{realm}}/protocol/openid-connect/token + refresh_token_url: + client_id: bruno + client_secret: {{client_secret}} + scope: openid + state: + pkce: false + credentials_placement: body + credentials_id: credentials + token_source: access_token + token_placement: header + token_header_prefix: Bearer + auto_fetch_token: true + auto_refresh_token: false +} diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru b/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru new file mode 100644 index 00000000000..0275a1f04ee --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru @@ -0,0 +1,25 @@ +meta { + name: AuthorizationImplicit + type: http + seq: 2 +} + +get { + url: {{userinfo_url}} + body: none + auth: oauth2 +} + +auth:oauth2 { + grant_type: implicit + callback_url: bruno://app/oauth2/callback + authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth + client_id: bruno + scope: openid + state: + credentials_id: credentials + token_source: access_token + token_placement: header + token_header_prefix: Bearer + auto_fetch_token: true +} diff --git a/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru b/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru new file mode 100644 index 00000000000..5a7479f2c97 --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru @@ -0,0 +1,25 @@ +meta { + name: ImplicitUserSuppliedState + type: http + seq: 4 +} + +get { + url: {{userinfo_url}} + body: none + auth: oauth2 +} + +auth:oauth2 { + grant_type: implicit + callback_url: bruno://app/oauth2/callback + authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth + client_id: bruno + scope: openid + state: brunoUserState + credentials_id: credentials + token_source: access_token + token_placement: header + token_header_prefix: Bearer + auto_fetch_token: true +} diff --git a/tests/auth/oauth2/fixtures/collection/bruno.json b/tests/auth/oauth2/fixtures/collection/bruno.json new file mode 100644 index 00000000000..c2925567f67 --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/bruno.json @@ -0,0 +1,5 @@ +{ + "version": "1", + "name": "oauth2-state", + "type": "collection" +} diff --git a/tests/auth/oauth2/fixtures/collection/environments/Local.bru b/tests/auth/oauth2/fixtures/collection/environments/Local.bru new file mode 100644 index 00000000000..3311c57a16c --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/environments/Local.bru @@ -0,0 +1,6 @@ +vars { + host: http://127.0.0.1:8090 + realm: bruno + client_secret: DSH25NOw5mMOCEIMrmm31EtUad4TbRLM + userinfo_url: http://127.0.0.1:8090/realms/bruno/protocol/openid-connect/userinfo +} diff --git a/tests/auth/oauth2/fixtures/keycloak/realm-export.json b/tests/auth/oauth2/fixtures/keycloak/realm-export.json new file mode 100644 index 00000000000..79fce74dd2f --- /dev/null +++ b/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 + } + ] + } + ] +} \ No newline at end of file diff --git a/tests/auth/oauth2/init-user-data/preferences.json b/tests/auth/oauth2/init-user-data/preferences.json new file mode 100644 index 00000000000..ed131810837 --- /dev/null +++ b/tests/auth/oauth2/init-user-data/preferences.json @@ -0,0 +1,11 @@ +{ + "maximized": false, + "lastOpenedCollections": ["{{collectionPath}}"], + "preferences": { + "request": { + "oauth2": { + "useSystemBrowser": true + } + } + } +} diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts new file mode 100644 index 00000000000..72829a18163 --- /dev/null +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -0,0 +1,351 @@ +// use this command to start the keycloak server: and make sure that you update the path of the realm-export.json file +// docker run -d --name bruno-keycloak \ +// -p 8090:8080 \ +// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ +// -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ +// -v :/opt/keycloak/data/import/realm-export.json:ro \ +// quay.io/keycloak/keycloak:26.0 \ +// start-dev --http-port=8080 --import-realm + +import type { ElectronApplication } from 'playwright'; +import { test, expect, waitForReadyPage } from '../../../playwright'; +import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; +import { buildCommonLocators } from '../../utils/page/locators'; + +const COLLECTION = 'oauth2-state'; +const KEYCLOAK = 'http://127.0.0.1:8090'; +const KEYCLOAK_REALM = 'bruno'; +const KEYCLOAK_USER = 'testuser'; +const KEYCLOAK_PASSWORD = 'testpassword'; +const CALLBACK = '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 STATE_MISMATCH_ERROR + = 'OAuth2 state mismatch: the returned state does not match the issued state.'; + +test.beforeAll(async () => { + const response = await fetch(`${KEYCLOAK}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`); + expect( + response.ok, + `Keycloak realm "${KEYCLOAK_REALM}" should be reachable at ${KEYCLOAK}` + ).toBeTruthy(); +}); + +const loginToKeycloakForAuthCode = 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(); + const formActionMatch = html.match(/action="([^"]+login-actions\/authenticate[^"]*)"/); // extract the form action URL from the login page + expect(formActionMatch, 'Keycloak login page should expose a form action').toBeTruthy(); + const formAction = formActionMatch![1].replace(/&/g, '&'); // replace & with & to avoid URL encoding issues + + 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(); + const code = new URL(location as string).searchParams.get('code'); + expect(code, 'Keycloak callback redirect should carry an auth code').toBeTruthy(); + return code as string; +}; + +/** Fire a deep-link callback through the real protocol handler (cross-platform path). */ +const fireCallback = (app: ElectronApplication, url: string) => + app.evaluate(({ app: electronApp }, callbackUrl) => { + electronApp.emit('second-instance', {}, [callbackUrl]); + }, url); + +/** + * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno + * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. + */ +const installCallbackCapture = (app: ElectronApplication) => { + return app.evaluate(({ app: electronApp }) => { + (globalThis as any).__brunoCapturedCallbackUrl = null; + + electronApp.prependListener('second-instance', (_event, commandLine) => { + const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); + if (url) { + (globalThis as any).__brunoCapturedCallbackUrl = url; + } + }); + }); +}; + +const getCapturedCallbackUrl = (app: ElectronApplication): Promise => + app.evaluate(() => (globalThis as any).__brunoCapturedCallbackUrl ?? null); + +// 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. +const stubOpenExternal = (app: ElectronApplication) => + app.evaluate(({ shell }) => { + (globalThis as any).__brunoCapturedAuthUrl = null; + shell.openExternal = async (url: string) => { + (globalThis as any).__brunoCapturedAuthUrl = url; + }; + }); + +const getCapturedAuthUrl = (app: ElectronApplication): Promise => + app.evaluate(() => (globalThis as any).__brunoCapturedAuthUrl ?? null); + +const waitForAuthorizationStarted = async (app: ElectronApplication) => { + await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); +}; + +type CallbackStyle = 'query' | 'hash'; + +const stateFromAuthorizationUrl = (url: string) => new URL(url).searchParams.get('state'); + +/** `state` Bruno sent on the authorization URL (stored internally as expectedState). */ +const getIssuedState = async (app: ElectronApplication): Promise => { + const authUrl = await getCapturedAuthUrl(app); + expect(authUrl, 'authorization URL should have been opened').toBeTruthy(); + const state = stateFromAuthorizationUrl(authUrl as string); + expect(state, 'issued state should be present on the authorization URL').toBeTruthy(); + // expect((state as string).length).toBeGreaterThanOrEqual(STATE_NONCE_HEX_LENGTH); + return state as string; +}; + +const clickGetAccessToken = async (page: Parameters[0], requestName: string) => { + await openRequest(page, COLLECTION, requestName); + await selectEnvironment(page, 'Local', 'collection'); + await selectRequestPaneTab(page, 'Auth'); + await page.getByRole('button', { name: 'Get Access Token' }).click(); +}; + +/** + * Common flow bootstrap shared by every test: restart the app, wait for a ready page, + * stub `shell.openExternal`, install the callback capture, click "Get Access Token" for + * the given request, and wait for the authorization URL to be captured. + */ +const startOAuth2Flow = async ( + restartApp: (options?: { initUserDataPath?: string }) => Promise, + requestName: string +) => { + const app = await restartApp(); + const page = await waitForReadyPage(app); + + await stubOpenExternal(app); // fake opening the browser so we can read the login URL + await installCallbackCapture(app); + await clickGetAccessToken(page, requestName); + await waitForAuthorizationStarted(app); + + return { app, page }; +}; + +const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => { + const url = new URL(callbackUrl); + if (style === 'hash') { + const hashParams = new URLSearchParams(url.hash.slice(1)); + return { + state: hashParams.get('state'), + code: null, + access_token: hashParams.get('access_token') + }; + } + return { + state: url.searchParams.get('state'), + code: url.searchParams.get('code'), + access_token: null + }; +}; + +test.describe('OAuth2 callback state validation', () => { + test('authorization code: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { + test.setTimeout(60_000); + const USER_STATE = 'brunoUserState'; + 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 getIssuedState(app); + expect(state).toBe(USER_STATE); + return state; + }); + + const authCode = await test.step('obtain a valid auth code from Keycloak', () => + loginToKeycloakForAuthCode(authUrl as string)); + + const callbackUrl = `${CALLBACK}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + + await test.step('deliver a callback with the matching state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); + expect(returnedState).toBe(issuedState); + expect(code).toBe(authCode); + }); + + await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + }); + + test('authorization code: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { + test.setTimeout(60_000); + 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 getIssuedState(app); + // No user state was configured, so Bruno must generate a random 32-char hex string + // (crypto.randomBytes(16).toString('hex')). + expect(state).toMatch(/^[0-9a-f]{32}$/); + return state; + }); + + const authCode = await test.step('obtain a valid auth code from Keycloak', () => + loginToKeycloakForAuthCode(authUrl as string)); + + const callbackUrl = `${CALLBACK}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + + await test.step('deliver a callback with the matching state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); + expect(returnedState).toBe(issuedState); + expect(code).toBe(authCode); + }); + + await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + }); + + test('authorization code: rejects callback when returned state does not match issued state', async ({ restartApp }) => { + test.setTimeout(60_000); + + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode'); + + const issuedState = await getIssuedState(app); + + const callbackUrl = `${CALLBACK}?code=${PROVIDER_AUTH_CODE}&state=${WRONG_STATE}`; + await test.step('deliver a callback with a mismatched state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); + expect(returnedState).toBe(WRONG_STATE); + expect(returnedState).not.toBe(issuedState); + expect(code).toBe(PROVIDER_AUTH_CODE); + }); + + await test.step('Check for mismatch error in the response pane', async () => { + await expect( + buildCommonLocators(page).response.pane().getByText(STATE_MISMATCH_ERROR) + ).toBeVisible({ timeout: 15_000 }); + }); + }); + + test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { + test.setTimeout(60_000); + const USER_STATE = 'brunoUserState'; + const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState'); + + const issuedState = await test.step('capture and verify the issued state carries userState', async () => { + const state = await getIssuedState(app); + expect(state).toBe(USER_STATE); + return state; + }); + + const callbackUrl + = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + + await test.step('deliver a callback with the matching state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); + expect(returnedState).toBe(issuedState); + expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); + }); + + await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + }); + + test('implicit grant: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { + test.setTimeout(60_000); + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); + + const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => { + const state = await getIssuedState(app); + // No user state was configured, so Bruno must generate a random 32-char hex string + // (crypto.randomBytes(16).toString('hex')). + expect(state).toMatch(/^[0-9a-f]{32}$/); + return state; + }); + + const callbackUrl + = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + + await test.step('deliver a callback with the matching state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); + expect(returnedState).toBe(issuedState); + expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); + }); + + await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + }); + + test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => { + test.setTimeout(60_000); + const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); + + const issuedState = await test.step('capture the issued state', () => getIssuedState(app)); + + const callbackUrl = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&state=${WRONG_STATE}`; + + await test.step('deliver a callback with a mismatched state', async () => { + await fireCallback(app, callbackUrl); + + const receivedCallbackUrl = await getCapturedCallbackUrl(app); + expect(receivedCallbackUrl).toBe(callbackUrl); + + const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); + expect(returnedState).toBe(WRONG_STATE); + expect(returnedState).not.toBe(issuedState); + expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); + }); + + await test.step('surface a state mismatch error', async () => { + await expect( + buildCommonLocators(page).response.pane().getByText(STATE_MISMATCH_ERROR) + ).toBeVisible({ timeout: 15_000 }); + }); + }); +}); From 5c8b4e478ad2fdf42b6408eb105822a191fda9c0 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 11 Sep 2026 13:52:21 +0530 Subject: [PATCH 02/25] ci(oauth2): extract Keycloak zip with unzip, fall back to tar GNU tar on the ubuntu runner does not read zip archives. Use unzip where present (Linux, macOS, Git Bash on Windows) and keep tar as the fallback. --- .github/actions/auth/oauth2/setup-keycloak/action.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index 2b09435a8bd..1596dc1eee3 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -21,7 +21,8 @@ runs: # step completes — so a server started in this step would be killed before the test step # runs. It is downloaded/prepared here and started in the shared step that runs the tests # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three - # runner OSes (Git Bash on Windows); tar extracts zips everywhere, unlike unzip. + # runner OSes (Git Bash on Windows). unzip exists on Linux/macOS and in Git Bash; GNU tar on + # Linux cannot read zips, so tar (bsdtar on macOS/Windows) is only the fallback. - name: Download and prepare Keycloak shell: bash env: @@ -31,7 +32,11 @@ runs: curl -fsSL -o "${RUNNER_TEMP}/keycloak.zip" \ "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.zip" - tar -xf "${RUNNER_TEMP}/keycloak.zip" -C "${RUNNER_TEMP}" + if command -v unzip > /dev/null 2>&1; then + unzip -qo "${RUNNER_TEMP}/keycloak.zip" -d "${RUNNER_TEMP}" + else + tar -xf "${RUNNER_TEMP}/keycloak.zip" -C "${RUNNER_TEMP}" + fi KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" mkdir -p "${KC_HOME}/data/import" From 4563b943bbc4d4bf28b6a7ba75a624abd39e45fa Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 11 Sep 2026 13:59:56 +0530 Subject: [PATCH 03/25] ci(oauth2): switch from Keycloak zip to tar.gz for extraction Updated the Keycloak setup action to download and extract the .tar.gz file instead of the .zip. This simplifies the extraction process by using `tar -xzf`, which is compatible across all supported OSes, eliminating the need for OS-specific extraction logic. --- .../actions/auth/oauth2/setup-keycloak/action.yml | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index 1596dc1eee3..d9bfe8f0d20 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -21,8 +21,9 @@ runs: # step completes — so a server started in this step would be killed before the test step # runs. It is downloaded/prepared here and started in the shared step that runs the tests # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three - # runner OSes (Git Bash on Windows). unzip exists on Linux/macOS and in Git Bash; GNU tar on - # Linux cannot read zips, so tar (bsdtar on macOS/Windows) is only the fallback. + # runner OSes (Git Bash on Windows). Keycloak ships a .tar.gz alongside the .zip, and + # `tar -xzf` behaves identically on GNU tar (Linux) and bsdtar (macOS, Windows), so no + # per-OS extraction branch is needed. - name: Download and prepare Keycloak shell: bash env: @@ -30,13 +31,9 @@ runs: run: | set -euo pipefail - curl -fsSL -o "${RUNNER_TEMP}/keycloak.zip" \ - "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.zip" - if command -v unzip > /dev/null 2>&1; then - unzip -qo "${RUNNER_TEMP}/keycloak.zip" -d "${RUNNER_TEMP}" - else - tar -xf "${RUNNER_TEMP}/keycloak.zip" -C "${RUNNER_TEMP}" - fi + curl -fsSL -o "${RUNNER_TEMP}/keycloak.tar.gz" \ + "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.tar.gz" + tar -xzf "${RUNNER_TEMP}/keycloak.tar.gz" -C "${RUNNER_TEMP}" KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" mkdir -p "${KC_HOME}/data/import" From 91a48fd5fd6e79b2aaf3c5eff19484646ddc868b Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 11 Sep 2026 14:10:09 +0530 Subject: [PATCH 04/25] ci(oauth2): refine Keycloak setup action for tar.gz extraction Updated the Keycloak setup action to streamline the extraction process by addressing the tar.gz file directly from the RUNNER_TEMP directory. This change enhances compatibility across all runner OSes by avoiding issues with path interpretation in GNU tar on Windows. --- .../actions/auth/oauth2/setup-keycloak/action.yml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index d9bfe8f0d20..defbfa39228 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -21,9 +21,10 @@ runs: # step completes — so a server started in this step would be killed before the test step # runs. It is downloaded/prepared here and started in the shared step that runs the tests # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three - # runner OSes (Git Bash on Windows). Keycloak ships a .tar.gz alongside the .zip, and - # `tar -xzf` behaves identically on GNU tar (Linux) and bsdtar (macOS, Windows), so no - # per-OS extraction branch is needed. + # runner OSes (Git Bash on Windows). Keycloak ships a .tar.gz alongside the .zip, which every + # runner's tar can extract. The archive is addressed by a relative name from inside + # RUNNER_TEMP because GNU tar (Linux, Git Bash) reads the colon in a Windows path such as + # D:\a\_temp\keycloak.tar.gz as a remote host and fails with "Cannot connect to D". - name: Download and prepare Keycloak shell: bash env: @@ -31,9 +32,10 @@ runs: run: | set -euo pipefail - curl -fsSL -o "${RUNNER_TEMP}/keycloak.tar.gz" \ + cd "${RUNNER_TEMP}" + curl -fsSL -o keycloak.tar.gz \ "https://github.com/keycloak/keycloak/releases/download/${KEYCLOAK_VERSION}/keycloak-${KEYCLOAK_VERSION}.tar.gz" - tar -xzf "${RUNNER_TEMP}/keycloak.tar.gz" -C "${RUNNER_TEMP}" + tar -xzf keycloak.tar.gz KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" mkdir -p "${KC_HOME}/data/import" From 8164293589e5d578638f3d0c7ac32be6850534c7 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 11 Sep 2026 16:28:55 +0530 Subject: [PATCH 05/25] update comments --- .../actions/auth/oauth2/setup-keycloak/action.yml | 3 +-- .../Auth/OAuth2/Oauth2ActionButtons/index.js | 2 +- packages/bruno-electron/src/utils/oauth2.js | 4 ++-- tests/auth/oauth2/oauth2-state-validation.spec.ts | 15 ++++++--------- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index defbfa39228..e96814e3f1f 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -21,8 +21,7 @@ runs: # step completes — so a server started in this step would be killed before the test step # runs. It is downloaded/prepared here and started in the shared step that runs the tests # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three - # runner OSes (Git Bash on Windows). Keycloak ships a .tar.gz alongside the .zip, which every - # runner's tar can extract. The archive is addressed by a relative name from inside + # runner OSes (Git Bash on Windows). The tarball is addressed by a relative name from inside # RUNNER_TEMP because GNU tar (Linux, Git Bash) reads the colon in a Windows path such as # D:\a\_temp\keycloak.tar.gz as a remote host and fails with "Cannot connect to D". - name: Download and prepare Keycloak 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 6e57463ccf2..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,7 @@ 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, responseCleared } from 'providers/ReduxStore/slices/collections'; +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'; diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index a627853e75c..ec3742ec9d5 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -713,8 +713,8 @@ const generateCodeVerifier = () => { }; // Build an OAuth2 state string to help prevent CSRF and forged auth codes. -// If the user supplies a non-empty state, it is used as-is; otherwise a -// cryptographically random value is generated. +// 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/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index 72829a18163..36449278a39 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -1,11 +1,9 @@ -// use this command to start the keycloak server: and make sure that you update the path of the realm-export.json file -// docker run -d --name bruno-keycloak \ -// -p 8090:8080 \ -// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ -// -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ -// -v :/opt/keycloak/data/import/realm-export.json:ro \ -// quay.io/keycloak/keycloak:26.0 \ -// start-dev --http-port=8080 --import-realm +// These tests need a Keycloak with the fixture realm imported, listening on 127.0.0.1:8090. +// CI provisions it via .github/actions/auth/oauth2/setup-keycloak. Locally, from the repo root: +// docker run -d --name bruno-keycloak -p 8090:8080 \ +// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ +// -v "$PWD/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ +// quay.io/keycloak/keycloak:26.0 start-dev --http-port=8080 --import-realm import type { ElectronApplication } from 'playwright'; import { test, expect, waitForReadyPage } from '../../../playwright'; @@ -120,7 +118,6 @@ const getIssuedState = async (app: ElectronApplication): Promise => { expect(authUrl, 'authorization URL should have been opened').toBeTruthy(); const state = stateFromAuthorizationUrl(authUrl as string); expect(state, 'issued state should be present on the authorization URL').toBeTruthy(); - // expect((state as string).length).toBeGreaterThanOrEqual(STATE_NONCE_HEX_LENGTH); return state as string; }; From e58f084172de9d6e2fa1da0274dcb72e7fea08d1 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 6 Oct 2026 17:56:28 +0530 Subject: [PATCH 06/25] update test files from .bru to .yml --- .../collection/AuthCodeUserSuppliedState.bru | 31 ---------------- .../collection/AuthCodeUserSuppliedState.yml | 37 +++++++++++++++++++ .../fixtures/collection/AuthorizationCode.bru | 31 ---------------- .../fixtures/collection/AuthorizationCode.yml | 36 ++++++++++++++++++ .../collection/AuthorizationImplicit.bru | 25 ------------- .../collection/AuthorizationImplicit.yml | 30 +++++++++++++++ .../collection/ImplicitUserSuppliedState.bru | 25 ------------- .../collection/ImplicitUserSuppliedState.yml | 31 ++++++++++++++++ .../collection/environments/Local.bru | 6 --- .../collection/environments/Local.yml | 9 +++++ .../fixtures/collection/opencollection.yml | 3 ++ 11 files changed, 146 insertions(+), 118 deletions(-) delete mode 100644 tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru create mode 100644 tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml delete mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru create mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml delete mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru create mode 100644 tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml delete mode 100644 tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru create mode 100644 tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml delete mode 100644 tests/auth/oauth2/fixtures/collection/environments/Local.bru create mode 100644 tests/auth/oauth2/fixtures/collection/environments/Local.yml create mode 100644 tests/auth/oauth2/fixtures/collection/opencollection.yml diff --git a/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru b/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru deleted file mode 100644 index daad1468144..00000000000 --- a/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.bru +++ /dev/null @@ -1,31 +0,0 @@ -meta { - name: AuthCodeUserSuppliedState - type: http - seq: 3 -} - -get { - url: {{userinfo_url}} - body: none - auth: oauth2 -} - -auth:oauth2 { - grant_type: authorization_code - callback_url: bruno://app/oauth2/callback - authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth - access_token_url: {{host}}/realms/{{realm}}/protocol/openid-connect/token - refresh_token_url: - client_id: bruno - client_secret: {{client_secret}} - scope: openid - state: brunoUserState - pkce: false - credentials_placement: body - credentials_id: credentials - token_source: access_token - token_placement: header - token_header_prefix: Bearer - auto_fetch_token: true - auto_refresh_token: false -} diff --git a/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml b/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml new file mode 100644 index 00000000000..518864b2def --- /dev/null +++ b/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/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru b/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru deleted file mode 100644 index 5aeb75acf0e..00000000000 --- a/tests/auth/oauth2/fixtures/collection/AuthorizationCode.bru +++ /dev/null @@ -1,31 +0,0 @@ -meta { - name: AuthorizationCode - type: http - seq: 1 -} - -get { - url: {{userinfo_url}} - body: none - auth: oauth2 -} - -auth:oauth2 { - grant_type: authorization_code - callback_url: bruno://app/oauth2/callback - authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth - access_token_url: {{host}}/realms/{{realm}}/protocol/openid-connect/token - refresh_token_url: - client_id: bruno - client_secret: {{client_secret}} - scope: openid - state: - pkce: false - credentials_placement: body - credentials_id: credentials - token_source: access_token - token_placement: header - token_header_prefix: Bearer - auto_fetch_token: true - auto_refresh_token: false -} diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml b/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml new file mode 100644 index 00000000000..b6b000a45d9 --- /dev/null +++ b/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/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru b/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru deleted file mode 100644 index 0275a1f04ee..00000000000 --- a/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.bru +++ /dev/null @@ -1,25 +0,0 @@ -meta { - name: AuthorizationImplicit - type: http - seq: 2 -} - -get { - url: {{userinfo_url}} - body: none - auth: oauth2 -} - -auth:oauth2 { - grant_type: implicit - callback_url: bruno://app/oauth2/callback - authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth - client_id: bruno - scope: openid - state: - credentials_id: credentials - token_source: access_token - token_placement: header - token_header_prefix: Bearer - auto_fetch_token: true -} diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml b/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml new file mode 100644 index 00000000000..58285711612 --- /dev/null +++ b/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/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru b/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru deleted file mode 100644 index 5a7479f2c97..00000000000 --- a/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.bru +++ /dev/null @@ -1,25 +0,0 @@ -meta { - name: ImplicitUserSuppliedState - type: http - seq: 4 -} - -get { - url: {{userinfo_url}} - body: none - auth: oauth2 -} - -auth:oauth2 { - grant_type: implicit - callback_url: bruno://app/oauth2/callback - authorization_url: {{host}}/realms/{{realm}}/protocol/openid-connect/auth - client_id: bruno - scope: openid - state: brunoUserState - credentials_id: credentials - token_source: access_token - token_placement: header - token_header_prefix: Bearer - auto_fetch_token: true -} diff --git a/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml b/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml new file mode 100644 index 00000000000..72b7490ca9e --- /dev/null +++ b/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/tests/auth/oauth2/fixtures/collection/environments/Local.bru b/tests/auth/oauth2/fixtures/collection/environments/Local.bru deleted file mode 100644 index 3311c57a16c..00000000000 --- a/tests/auth/oauth2/fixtures/collection/environments/Local.bru +++ /dev/null @@ -1,6 +0,0 @@ -vars { - host: http://127.0.0.1:8090 - realm: bruno - client_secret: DSH25NOw5mMOCEIMrmm31EtUad4TbRLM - userinfo_url: http://127.0.0.1:8090/realms/bruno/protocol/openid-connect/userinfo -} diff --git a/tests/auth/oauth2/fixtures/collection/environments/Local.yml b/tests/auth/oauth2/fixtures/collection/environments/Local.yml new file mode 100644 index 00000000000..03c7059f42f --- /dev/null +++ b/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/tests/auth/oauth2/fixtures/collection/opencollection.yml b/tests/auth/oauth2/fixtures/collection/opencollection.yml new file mode 100644 index 00000000000..b8e7893c705 --- /dev/null +++ b/tests/auth/oauth2/fixtures/collection/opencollection.yml @@ -0,0 +1,3 @@ +opencollection: "1.0.0" +info: + name: oauth2-state From 4d100a2fc3e519bef14da31f606691d5d6217b06 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 6 Oct 2026 17:57:04 +0530 Subject: [PATCH 07/25] refactor(oauth2): remove outdated comments and streamline state generation --- packages/bruno-electron/src/utils/oauth2.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index ec3742ec9d5..6d6fa9d82f1 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -308,9 +308,7 @@ 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); From b7f37a402329c79bde767ddd293febee8c2810f5 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 6 Oct 2026 18:02:04 +0530 Subject: [PATCH 08/25] docs(oauth2): update local Keycloak setup instructions for state validation tests --- tests/auth/oauth2/oauth2-state-validation.spec.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index 36449278a39..bd8271fd766 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -1,7 +1,9 @@ -// These tests need a Keycloak with the fixture realm imported, listening on 127.0.0.1:8090. -// CI provisions it via .github/actions/auth/oauth2/setup-keycloak. Locally, from the repo root: +// To test the OAuth2 state validation locally, start a Keycloak instance +// with the fixture realm imported with the following command: +// // docker run -d --name bruno-keycloak -p 8090:8080 \ -// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ +// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ +// -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ // -v "$PWD/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ // quay.io/keycloak/keycloak:26.0 start-dev --http-port=8080 --import-realm From 233c52ee21cd962fa1fd3b6852e9945e75c9fe4a Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Thu, 15 Oct 2026 15:22:25 +0530 Subject: [PATCH 09/25] Resolve review comments --- .../auth/oauth2/collect-keycloak-logs/action.yml | 3 ++- .../auth/oauth2/run-oauth2-e2e-tests/action.yml | 8 ++------ .../actions/auth/oauth2/setup-keycloak/action.yml | 13 +++---------- .github/workflows/tests-linux.yml | 1 - 4 files changed, 7 insertions(+), 18 deletions(-) diff --git a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml index c4efad85dd0..3566242c962 100644 --- a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -22,7 +22,8 @@ runs: if (( ${#logs[@]} )); then cp "${logs[@]}" keycloak-logs/ else - echo "No Keycloak logs found in $RUNNER_TEMP." + echo "::error::No Keycloak logs found in $RUNNER_TEMP." + exit 1 fi - name: Upload Keycloak logs diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml index f8ab774cdcd..fdda967032f 100644 --- a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -2,10 +2,6 @@ name: 'Run OAuth2 E2E Tests' description: 'Start Keycloak and run the OAuth2 (Keycloak) E2E tests on Linux, macOS and Windows' inputs: - use-xvfb: - description: 'Wrap the test run in xvfb-run (needed on headless Linux)' - required: false - default: 'false' port: description: 'HTTP port Keycloak listens on' required: false @@ -25,7 +21,6 @@ runs: - name: Start Keycloak and run OAuth2 E2E tests shell: bash env: - USE_XVFB: ${{ inputs.use-xvfb }} KEYCLOAK_PORT: ${{ inputs.port }} run: | set -euo pipefail @@ -62,7 +57,8 @@ runs: fi echo "Keycloak is ready." - if [ "${USE_XVFB}" = "true" ]; then + # 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 diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index e96814e3f1f..95ab0cb81b1 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -15,23 +15,16 @@ runs: with: distribution: temurin java-version: '21' - - # NOTE: Keycloak is intentionally NOT started here. On Windows, GitHub Actions runs each - # step inside a Job Object that terminates the step's entire child-process tree when the - # step completes — so a server started in this step would be killed before the test step - # runs. It is downloaded/prepared here and started in the shared step that runs the tests - # (run-oauth2-e2e-tests). KC_HOME is exported for that step. bash is available on all three - # runner OSes (Git Bash on Windows). The tarball is addressed by a relative name from inside - # RUNNER_TEMP because GNU tar (Linux, Git Bash) reads the colon in a Windows path such as - # D:\a\_temp\keycloak.tar.gz as a remote host and fails with "Cannot connect to D". + # NOTE: On Windows, GitHub Actions terminates child process tree when the step completes. + # So keycloak is started in the same step where tests are ran. - name: Download and prepare Keycloak shell: bash + working-directory: ${{ runner.temp }} env: KEYCLOAK_VERSION: ${{ inputs.keycloak-version }} run: | set -euo pipefail - cd "${RUNNER_TEMP}" 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 diff --git a/.github/workflows/tests-linux.yml b/.github/workflows/tests-linux.yml index df0b464aec7..e0c3469839c 100644 --- a/.github/workflows/tests-linux.yml +++ b/.github/workflows/tests-linux.yml @@ -253,7 +253,6 @@ jobs: - name: Run OAuth2 E2E Tests uses: ./.github/actions/auth/oauth2/run-oauth2-e2e-tests with: - use-xvfb: 'true' artifact-suffix: linux # Runs even when setup-keycloak or the test step failed, so a broken IdP is debuggable. From cd1b63c5234d7ca4f988e6460c0c40c5c93b73c5 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Thu, 15 Oct 2026 21:16:26 +0530 Subject: [PATCH 10/25] resolve code review suggestions --- .../oauth2/oauth2-state-validation.spec.ts | 146 +++++++++--------- 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index bd8271fd766..d8a001de95d 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -13,22 +13,25 @@ import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../util import { buildCommonLocators } from '../../utils/page/locators'; const COLLECTION = 'oauth2-state'; -const KEYCLOAK = 'http://127.0.0.1:8090'; +const KEYCLOAK_BASE_URL = 'http://127.0.0.1:8090'; const KEYCLOAK_REALM = 'bruno'; const KEYCLOAK_USER = 'testuser'; const KEYCLOAK_PASSWORD = 'testpassword'; -const CALLBACK = 'bruno://app/oauth2/callback'; +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'; +// Bruno issues crypto.randomBytes(16).toString('hex') when no user state is configured. +const GENERATED_STATE_PATTERN = /^[0-9a-f]{32}$/; const STATE_MISMATCH_ERROR = 'OAuth2 state mismatch: the returned state does not match the issued state.'; +// TODO: Move all utility functions to a separate file. (-helper.ts) test.beforeAll(async () => { - const response = await fetch(`${KEYCLOAK}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`); + 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}` + `Keycloak realm "${KEYCLOAK_REALM}" should be reachable at ${KEYCLOAK_BASE_URL}` ).toBeTruthy(); }); @@ -41,10 +44,15 @@ const loginToKeycloakForAuthCode = async (authorizationUrl: string): Promise +const fireDeepLinkCallback = (app: ElectronApplication, url: string) => app.evaluate(({ app: electronApp }, callbackUrl) => { electronApp.emit('second-instance', {}, [callbackUrl]); }, url); -/** - * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno - * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. - */ -const installCallbackCapture = (app: ElectronApplication) => { - return app.evaluate(({ app: electronApp }) => { - (globalThis as any).__brunoCapturedCallbackUrl = null; - - electronApp.prependListener('second-instance', (_event, commandLine) => { - const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); - if (url) { - (globalThis as any).__brunoCapturedCallbackUrl = url; - } - }); - }); -}; - const getCapturedCallbackUrl = (app: ElectronApplication): Promise => app.evaluate(() => (globalThis as any).__brunoCapturedCallbackUrl ?? null); +const getCapturedAuthUrl = (app: ElectronApplication): Promise => + app.evaluate(() => (globalThis as any).__brunoCapturedAuthUrl ?? null); + +/** `state` Bruno sent on the authorization URL (stored internally as expectedState). */ +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; +}; + // 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. @@ -103,24 +106,21 @@ const stubOpenExternal = (app: ElectronApplication) => }; }); -const getCapturedAuthUrl = (app: ElectronApplication): Promise => - app.evaluate(() => (globalThis as any).__brunoCapturedAuthUrl ?? null); - -const waitForAuthorizationStarted = async (app: ElectronApplication) => { - await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); -}; - -type CallbackStyle = 'query' | 'hash'; - -const stateFromAuthorizationUrl = (url: string) => new URL(url).searchParams.get('state'); +/** + * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno + * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. + */ +const installCallbackCapture = (app: ElectronApplication) => { + return app.evaluate(({ app: electronApp }) => { + (globalThis as any).__brunoCapturedCallbackUrl = null; -/** `state` Bruno sent on the authorization URL (stored internally as expectedState). */ -const getIssuedState = async (app: ElectronApplication): Promise => { - const authUrl = await getCapturedAuthUrl(app); - expect(authUrl, 'authorization URL should have been opened').toBeTruthy(); - const state = stateFromAuthorizationUrl(authUrl as string); - expect(state, 'issued state should be present on the authorization URL').toBeTruthy(); - return state as string; + electronApp.prependListener('second-instance', (_event, commandLine) => { + const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); + if (url) { + (globalThis as any).__brunoCapturedCallbackUrl = url; + } + }); + }); }; const clickGetAccessToken = async (page: Parameters[0], requestName: string) => { @@ -130,6 +130,10 @@ const clickGetAccessToken = async (page: Parameters[0], requ await page.getByRole('button', { name: 'Get Access Token' }).click(); }; +const waitForAuthorizationStarted = async (app: ElectronApplication) => { + await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); +}; + /** * Common flow bootstrap shared by every test: restart the app, wait for a ready page, * stub `shell.openExternal`, install the callback capture, click "Get Access Token" for @@ -142,14 +146,18 @@ const startOAuth2Flow = async ( const app = await restartApp(); const page = await waitForReadyPage(app); - await stubOpenExternal(app); // fake opening the browser so we can read the login URL + // Fake opening the browser so we can read the login URL. + await stubOpenExternal(app); await installCallbackCapture(app); + await clickGetAccessToken(page, requestName); await waitForAuthorizationStarted(app); return { app, page }; }; +type CallbackStyle = 'query' | 'hash'; + const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => { const url = new URL(callbackUrl); if (style === 'hash') { @@ -168,8 +176,10 @@ const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') }; 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 }) => { - test.setTimeout(60_000); const USER_STATE = 'brunoUserState'; const { app, page } = await startOAuth2Flow(restartApp, 'AuthCodeUserSuppliedState'); @@ -178,7 +188,7 @@ test.describe('OAuth2 callback state validation', () => { expect(authUrl).toBeTruthy(); const issuedState = await test.step('capture and verify the issued state carries userState', async () => { - const state = await getIssuedState(app); + const state = await getIssuedStateFromAuthorizationUrl(app); expect(state).toBe(USER_STATE); return state; }); @@ -186,10 +196,10 @@ test.describe('OAuth2 callback state validation', () => { const authCode = await test.step('obtain a valid auth code from Keycloak', () => loginToKeycloakForAuthCode(authUrl as string)); - const callbackUrl = `${CALLBACK}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; await test.step('deliver a callback with the matching state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); @@ -203,7 +213,6 @@ test.describe('OAuth2 callback state validation', () => { }); test('authorization code: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { - test.setTimeout(60_000); const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode'); const authUrl = await getCapturedAuthUrl(app); @@ -211,20 +220,18 @@ test.describe('OAuth2 callback state validation', () => { expect(authUrl).toBeTruthy(); const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => { - const state = await getIssuedState(app); - // No user state was configured, so Bruno must generate a random 32-char hex string - // (crypto.randomBytes(16).toString('hex')). - expect(state).toMatch(/^[0-9a-f]{32}$/); + 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', () => loginToKeycloakForAuthCode(authUrl as string)); - const callbackUrl = `${CALLBACK}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; + const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; await test.step('deliver a callback with the matching state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); @@ -238,15 +245,13 @@ test.describe('OAuth2 callback state validation', () => { }); test('authorization code: rejects callback when returned state does not match issued state', async ({ restartApp }) => { - test.setTimeout(60_000); - const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationCode'); - const issuedState = await getIssuedState(app); + const issuedState = await getIssuedStateFromAuthorizationUrl(app); - const callbackUrl = `${CALLBACK}?code=${PROVIDER_AUTH_CODE}&state=${WRONG_STATE}`; + const callbackUrl = `${CALLBACK_URL}?code=${PROVIDER_AUTH_CODE}&state=${WRONG_STATE}`; await test.step('deliver a callback with a mismatched state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); @@ -265,21 +270,20 @@ test.describe('OAuth2 callback state validation', () => { }); test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { - test.setTimeout(60_000); const USER_STATE = 'brunoUserState'; const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState'); const issuedState = await test.step('capture and verify the issued state carries userState', async () => { - const state = await getIssuedState(app); + const state = await getIssuedStateFromAuthorizationUrl(app); expect(state).toBe(USER_STATE); return state; }); const callbackUrl - = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; await test.step('deliver a callback with the matching state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); @@ -293,22 +297,19 @@ test.describe('OAuth2 callback state validation', () => { }); test('implicit grant: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { - test.setTimeout(60_000); const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); const issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => { - const state = await getIssuedState(app); - // No user state was configured, so Bruno must generate a random 32-char hex string - // (crypto.randomBytes(16).toString('hex')). - expect(state).toMatch(/^[0-9a-f]{32}$/); + const state = await getIssuedStateFromAuthorizationUrl(app); + expect(state).toMatch(GENERATED_STATE_PATTERN); return state; }); const callbackUrl - = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; await test.step('deliver a callback with the matching state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); @@ -322,15 +323,14 @@ test.describe('OAuth2 callback state validation', () => { }); test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => { - test.setTimeout(60_000); const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); - const issuedState = await test.step('capture the issued state', () => getIssuedState(app)); + const issuedState = await test.step('capture the issued state', () => getIssuedStateFromAuthorizationUrl(app)); - const callbackUrl = `${CALLBACK}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&state=${WRONG_STATE}`; + const callbackUrl = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&state=${WRONG_STATE}`; await test.step('deliver a callback with a mismatched state', async () => { - await fireCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); const receivedCallbackUrl = await getCapturedCallbackUrl(app); expect(receivedCallbackUrl).toBe(callbackUrl); From 4dd10db13901300d799af44c6609dbee0cc587ab Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Thu, 15 Oct 2026 21:31:06 +0530 Subject: [PATCH 11/25] refactor(oauth2): modularize OAuth2 flow helpers and clean up test setup - Moved utility functions related to OAuth2 flow into a separate helpers file for better organization and maintainability. - Removed outdated comments and streamlined the test setup process for state validation. - Updated imports to reflect the new structure and ensure clarity in the test file. --- tests/auth/oauth2/helpers.ts | 147 ++++++++++++++++ .../oauth2/oauth2-state-validation.spec.ts | 157 ++---------------- 2 files changed, 157 insertions(+), 147 deletions(-) create mode 100644 tests/auth/oauth2/helpers.ts diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts new file mode 100644 index 00000000000..aebc83064a5 --- /dev/null +++ b/tests/auth/oauth2/helpers.ts @@ -0,0 +1,147 @@ +import type { ElectronApplication } from 'playwright'; +import { expect, waitForReadyPage } from '../../../playwright'; +import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; + +export const COLLECTION = 'oauth2-state'; +export const KEYCLOAK_USER = 'testuser'; +export const KEYCLOAK_PASSWORD = 'testpassword'; + +// 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; + }; + }); + +/** + * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno + * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. + */ +export const installCallbackCapture = (app: ElectronApplication) => { + return app.evaluate(({ app: electronApp }) => { + (globalThis as any).__brunoCapturedCallbackUrl = null; + + electronApp.prependListener('second-instance', (_event, commandLine) => { + const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); + if (url) { + (globalThis as any).__brunoCapturedCallbackUrl = 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 page.getByRole('button', { name: 'Get Access Token' }).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(); +}; + +/** + * Common flow bootstrap shared by every test: restart the app, wait for a ready page, + * stub `shell.openExternal`, install the callback capture, click "Get Access Token" for + * the given request, and wait for the authorization URL to be captured. + */ +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 installCallbackCapture(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; +}; + +export const loginToKeycloakForAuthCode = 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(); + + const loginFormActionRegex = /action="([^"]+login-actions\/authenticate[^"]*)"/; + + // 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(); + const code = new URL(location as string).searchParams.get('code'); + expect(code, 'Keycloak callback redirect should carry an auth code').toBeTruthy(); + return code 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); + +export const getCapturedCallbackUrl = (app: ElectronApplication): Promise => + app.evaluate(() => (globalThis as any).__brunoCapturedCallbackUrl ?? null); + +export type CallbackStyle = 'query' | 'hash'; + +export const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => { + const url = new URL(callbackUrl); + if (style === 'hash') { + const hashParams = new URLSearchParams(url.hash.slice(1)); + return { + state: hashParams.get('state'), + code: null, + access_token: hashParams.get('access_token') + }; + } + return { + state: url.searchParams.get('state'), + code: url.searchParams.get('code'), + access_token: null + }; +}; diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index d8a001de95d..2580de8dcc7 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -7,16 +7,20 @@ // -v "$PWD/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ // quay.io/keycloak/keycloak:26.0 start-dev --http-port=8080 --import-realm -import type { ElectronApplication } from 'playwright'; -import { test, expect, waitForReadyPage } from '../../../playwright'; -import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; +import { test, expect } from '../../../playwright'; import { buildCommonLocators } from '../../utils/page/locators'; +import { + startOAuth2Flow, + getCapturedAuthUrl, + getIssuedStateFromAuthorizationUrl, + loginToKeycloakForAuthCode, + fireDeepLinkCallback, + getCapturedCallbackUrl, + getCallbackParams +} from './helpers'; -const COLLECTION = 'oauth2-state'; const KEYCLOAK_BASE_URL = 'http://127.0.0.1:8090'; const KEYCLOAK_REALM = 'bruno'; -const KEYCLOAK_USER = 'testuser'; -const KEYCLOAK_PASSWORD = 'testpassword'; const CALLBACK_URL = 'bruno://app/oauth2/callback'; const PROVIDER_AUTH_CODE = 'provider-auth-code'; const PROVIDER_ACCESS_TOKEN = 'provider-access-token'; @@ -26,7 +30,6 @@ const GENERATED_STATE_PATTERN = /^[0-9a-f]{32}$/; const STATE_MISMATCH_ERROR = 'OAuth2 state mismatch: the returned state does not match the issued state.'; -// TODO: Move all utility functions to a separate file. (-helper.ts) test.beforeAll(async () => { const response = await fetch(`${KEYCLOAK_BASE_URL}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`); expect( @@ -35,146 +38,6 @@ test.beforeAll(async () => { ).toBeTruthy(); }); -const loginToKeycloakForAuthCode = 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(); - - const loginFormActionRegex = /action="([^"]+login-actions\/authenticate[^"]*)"/; - - // 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(); - const code = new URL(location as string).searchParams.get('code'); - expect(code, 'Keycloak callback redirect should carry an auth code').toBeTruthy(); - return code as string; -}; - -/** Fire a deep-link callback through the real protocol handler (cross-platform path). */ -const fireDeepLinkCallback = (app: ElectronApplication, url: string) => - app.evaluate(({ app: electronApp }, callbackUrl) => { - electronApp.emit('second-instance', {}, [callbackUrl]); - }, url); - -const getCapturedCallbackUrl = (app: ElectronApplication): Promise => - app.evaluate(() => (globalThis as any).__brunoCapturedCallbackUrl ?? null); - -const getCapturedAuthUrl = (app: ElectronApplication): Promise => - app.evaluate(() => (globalThis as any).__brunoCapturedAuthUrl ?? null); - -/** `state` Bruno sent on the authorization URL (stored internally as expectedState). */ -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; -}; - -// 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. -const stubOpenExternal = (app: ElectronApplication) => - app.evaluate(({ shell }) => { - (globalThis as any).__brunoCapturedAuthUrl = null; - shell.openExternal = async (url: string) => { - (globalThis as any).__brunoCapturedAuthUrl = url; - }; - }); - -/** - * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno - * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. - */ -const installCallbackCapture = (app: ElectronApplication) => { - return app.evaluate(({ app: electronApp }) => { - (globalThis as any).__brunoCapturedCallbackUrl = null; - - electronApp.prependListener('second-instance', (_event, commandLine) => { - const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); - if (url) { - (globalThis as any).__brunoCapturedCallbackUrl = url; - } - }); - }); -}; - -const clickGetAccessToken = async (page: Parameters[0], requestName: string) => { - await openRequest(page, COLLECTION, requestName); - await selectEnvironment(page, 'Local', 'collection'); - await selectRequestPaneTab(page, 'Auth'); - await page.getByRole('button', { name: 'Get Access Token' }).click(); -}; - -const waitForAuthorizationStarted = async (app: ElectronApplication) => { - await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); -}; - -/** - * Common flow bootstrap shared by every test: restart the app, wait for a ready page, - * stub `shell.openExternal`, install the callback capture, click "Get Access Token" for - * the given request, and wait for the authorization URL to be captured. - */ -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 installCallbackCapture(app); - - await clickGetAccessToken(page, requestName); - await waitForAuthorizationStarted(app); - - return { app, page }; -}; - -type CallbackStyle = 'query' | 'hash'; - -const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => { - const url = new URL(callbackUrl); - if (style === 'hash') { - const hashParams = new URLSearchParams(url.hash.slice(1)); - return { - state: hashParams.get('state'), - code: null, - access_token: hashParams.get('access_token') - }; - } - return { - state: url.searchParams.get('state'), - code: url.searchParams.get('code'), - access_token: null - }; -}; - 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 }); From 539052615d42796f61546df1444180bdd379e428 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 16 Oct 2026 13:42:53 +0530 Subject: [PATCH 12/25] refactor(oauth2): clean up action.yml files and enhance documentation - Removed outdated comments from the Keycloak log collection and OAuth2 E2E test action files for clarity. - Added documentation regarding external service requirements for specific projects in the Playwright testing guide. - Updated helper functions to improve readability and maintainability in the OAuth2 test suite. --- .../oauth2/collect-keycloak-logs/action.yml | 3 -- .../oauth2/run-oauth2-e2e-tests/action.yml | 7 ++-- docs/playwright-testing-guide.md | 7 ++++ tests/auth/oauth2/README.md | 34 +++++++++++++++++++ tests/auth/oauth2/helpers.ts | 14 +++----- .../oauth2/oauth2-state-validation.spec.ts | 9 +---- 6 files changed, 48 insertions(+), 26 deletions(-) create mode 100644 tests/auth/oauth2/README.md diff --git a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml index 3566242c962..43293ef9d09 100644 --- a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -9,9 +9,6 @@ inputs: runs: using: 'composite' steps: - # Keycloak logs live in RUNNER_TEMP (outside the workspace), so stage them into the - # workspace where upload-artifact can pick them up. bash is available on all three runner - # OSes (Git Bash on Windows), so one script covers them all. - name: Stage Keycloak logs shell: bash run: | diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml index fdda967032f..0838060e4e7 100644 --- a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -13,11 +13,8 @@ inputs: runs: using: 'composite' steps: - # Keycloak is started HERE — in the same step as the tests — on purpose. On Windows, - # GitHub Actions kills a step's child-process tree when the step ends (Job Object), so a - # server started in an earlier step is dead by the time tests run. Doing the same on every - # OS keeps a single script. KC_HOME comes from the setup-keycloak step. bash is available - # on all three runner OSes (Git Bash on Windows); kc.bat vs kc.sh is the only OS switch. + # Keycloak is started here and tests run in same step due cause Github Actions kills a child-process + # when the step ends. KC_HOME comes from the setup-keycloak step. - name: Start Keycloak and run OAuth2 E2E tests shell: bash env: 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/tests/auth/oauth2/README.md b/tests/auth/oauth2/README.md new file mode 100644 index 00000000000..21b039abe02 --- /dev/null +++ b/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/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/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index aebc83064a5..302cadf9138 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -6,9 +6,10 @@ export const COLLECTION = 'oauth2-state'; export const KEYCLOAK_USER = 'testuser'; export const KEYCLOAK_PASSWORD = 'testpassword'; -// 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. +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; @@ -48,11 +49,6 @@ export const waitForAuthorizationStarted = async (app: ElectronApplication) => { await expect.poll(() => getCapturedAuthUrl(app), { timeout: 15_000 }).toBeTruthy(); }; -/** - * Common flow bootstrap shared by every test: restart the app, wait for a ready page, - * stub `shell.openExternal`, install the callback capture, click "Get Access Token" for - * the given request, and wait for the authorization URL to be captured. - */ export const startOAuth2Flow = async ( restartApp: (options?: { initUserDataPath?: string }) => Promise, requestName: string @@ -89,8 +85,6 @@ export const loginToKeycloakForAuthCode = async (authorizationUrl: string): Prom const html = await loginPage.text(); - const loginFormActionRegex = /action="([^"]+login-actions\/authenticate[^"]*)"/; - // 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(); diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index 2580de8dcc7..1317135d962 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -1,11 +1,4 @@ -// To test the OAuth2 state validation locally, start a Keycloak instance -// with the fixture realm imported with the following command: -// -// docker run -d --name bruno-keycloak -p 8090:8080 \ -// -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ -// -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ -// -v "$PWD/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ -// quay.io/keycloak/keycloak:26.0 start-dev --http-port=8080 --import-realm +// Requires a local Keycloak instance; see ./README.md for setup. import { test, expect } from '../../../playwright'; import { buildCommonLocators } from '../../utils/page/locators'; From 77cef4d8bca0a8619b091c8911982fdc0824f821 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 16 Oct 2026 15:09:51 +0530 Subject: [PATCH 13/25] fix(oauth2): improve state mismatch handling in tests --- e2e/pages/request/auth.ts | 3 ++- .../Auth/OAuth2/Oauth2TokenViewer/index.js | 2 +- tests/auth/oauth2/helpers.ts | 16 +++++++++++++++- .../oauth2/oauth2-state-validation.spec.ts | 18 ++++-------------- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index 3af3336ae30..2b16b42c31e 100644 --- a/e2e/pages/request/auth.ts +++ b/e2e/pages/request/auth.ts @@ -46,7 +46,8 @@ 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') }, modeSelector: () => page.getByTestId('auth-mode-selector'), modeLabel: () => page.getByTestId('auth-mode-label'), 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..d82e4782f01 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 @@ -166,7 +166,7 @@ const Oauth2TokenViewer = ({ collection, item, url, credentialsId, handleRun }) ) ) : ( -
No token found
+
No token found
)} ); diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index 302cadf9138..4102c46e2d2 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -1,6 +1,7 @@ import type { ElectronApplication } from 'playwright'; -import { expect, waitForReadyPage } from '../../../playwright'; +import { test, expect, waitForReadyPage } from '../../../playwright'; import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; +import { buildCommonLocators } from '../../utils/page/locators'; export const COLLECTION = 'oauth2-state'; export const KEYCLOAK_USER = 'testuser'; @@ -139,3 +140,16 @@ export const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'q access_token: null }; }; + +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/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index 1317135d962..a561dd985e1 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -1,7 +1,6 @@ // Requires a local Keycloak instance; see ./README.md for setup. import { test, expect } from '../../../playwright'; -import { buildCommonLocators } from '../../utils/page/locators'; import { startOAuth2Flow, getCapturedAuthUrl, @@ -9,7 +8,8 @@ import { loginToKeycloakForAuthCode, fireDeepLinkCallback, getCapturedCallbackUrl, - getCallbackParams + getCallbackParams, + expectStateMismatchWithoutToken } from './helpers'; const KEYCLOAK_BASE_URL = 'http://127.0.0.1:8090'; @@ -20,8 +20,6 @@ const PROVIDER_ACCESS_TOKEN = 'provider-access-token'; const WRONG_STATE = 'not-the-issued-state'; // Bruno issues crypto.randomBytes(16).toString('hex') when no user state is configured. const GENERATED_STATE_PATTERN = /^[0-9a-f]{32}$/; -const STATE_MISMATCH_ERROR - = 'OAuth2 state mismatch: the returned state does not match the issued state.'; test.beforeAll(async () => { const response = await fetch(`${KEYCLOAK_BASE_URL}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`); @@ -118,11 +116,7 @@ test.describe('OAuth2 callback state validation', () => { expect(code).toBe(PROVIDER_AUTH_CODE); }); - await test.step('Check for mismatch error in the response pane', async () => { - await expect( - buildCommonLocators(page).response.pane().getByText(STATE_MISMATCH_ERROR) - ).toBeVisible({ timeout: 15_000 }); - }); + await expectStateMismatchWithoutToken(page); }); test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { @@ -197,10 +191,6 @@ test.describe('OAuth2 callback state validation', () => { expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); }); - await test.step('surface a state mismatch error', async () => { - await expect( - buildCommonLocators(page).response.pane().getByText(STATE_MISMATCH_ERROR) - ).toBeVisible({ timeout: 15_000 }); - }); + await expectStateMismatchWithoutToken(page); }); }); From 92eb02210a3dca5355f99e281d6b6784524ea9ee Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 16 Oct 2026 15:34:36 +0530 Subject: [PATCH 14/25] - Added data-testid attributes to the OAuth2 token viewer for improved testability. - Refactored OAuth2 test helpers to replace deprecated functions with a new method for reading fetched access tokens. - Updated state validation tests to utilize the new helper, simplifying the callback verification process. --- e2e/pages/request/auth.ts | 7 +- .../Auth/OAuth2/Oauth2TokenViewer/index.js | 3 +- tests/auth/oauth2/helpers.ts | 44 ++-------- .../oauth2/oauth2-state-validation.spec.ts | 86 +++---------------- 4 files changed, 25 insertions(+), 115 deletions(-) diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index 2b16b42c31e..ede91489137 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'), @@ -47,7 +49,8 @@ export const buildAuthLocators = (page: Page) => ({ clearCacheButton: () => page.getByRole('button', { name: 'Clear Cache' }), tokenSection: (title: string) => page.getByRole('heading', { name: title, exact: true }), copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }), - noToken: () => page.getByTestId('oauth2-no-token') + noToken: () => page.getByTestId('oauth2-no-token'), + tokenValue: (title: string) => page.getByTestId(`oauth2-token-value-${title}`) }, modeSelector: () => page.getByTestId('auth-mode-selector'), modeLabel: () => page.getByTestId('auth-mode-label'), 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 d82e4782f01..503c1578852 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 @@ -36,6 +36,7 @@ const TokenSection = ({ title, token }) => {
setIsExpanded(!isExpanded)} >
@@ -62,7 +63,7 @@ const TokenSection = ({ title, token }) => { : }
-
+
{token}
diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index 4102c46e2d2..ac92bf39981 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -19,23 +19,6 @@ export const stubOpenExternal = (app: ElectronApplication) => }; }); -/** - * Wrap the real `second-instance` listener so callback URLs are recorded when Bruno - * receives them — same argv path as `getAppProtocolUrlFromArgv` in index.js. - */ -export const installCallbackCapture = (app: ElectronApplication) => { - return app.evaluate(({ app: electronApp }) => { - (globalThis as any).__brunoCapturedCallbackUrl = null; - - electronApp.prependListener('second-instance', (_event, commandLine) => { - const url = commandLine?.find((arg: string) => arg?.startsWith('bruno://')); - if (url) { - (globalThis as any).__brunoCapturedCallbackUrl = url; - } - }); - }); -}; - export const clickGetAccessToken = async (page: Parameters[0], requestName: string) => { await openRequest(page, COLLECTION, requestName); await selectEnvironment(page, 'Local', 'collection'); @@ -59,7 +42,6 @@ export const startOAuth2Flow = async ( // Fake opening the browser so we can read the login URL. await stubOpenExternal(app); - await installCallbackCapture(app); await clickGetAccessToken(page, requestName); await waitForAuthorizationStarted(app); @@ -119,26 +101,12 @@ export const fireDeepLinkCallback = (app: ElectronApplication, url: string) => electronApp.emit('second-instance', {}, [callbackUrl]); }, url); -export const getCapturedCallbackUrl = (app: ElectronApplication): Promise => - app.evaluate(() => (globalThis as any).__brunoCapturedCallbackUrl ?? null); - -export type CallbackStyle = 'query' | 'hash'; - -export const getCallbackParams = (callbackUrl: string, style: CallbackStyle = 'query') => { - const url = new URL(callbackUrl); - if (style === 'hash') { - const hashParams = new URLSearchParams(url.hash.slice(1)); - return { - state: hashParams.get('state'), - code: null, - access_token: hashParams.get('access_token') - }; - } - return { - state: url.searchParams.get('state'), - code: url.searchParams.get('code'), - access_token: null - }; +/** 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 diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index a561dd985e1..a62f8d9dce4 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -7,8 +7,7 @@ import { getIssuedStateFromAuthorizationUrl, loginToKeycloakForAuthCode, fireDeepLinkCallback, - getCapturedCallbackUrl, - getCallbackParams, + readFetchedAccessToken, expectStateMismatchWithoutToken } from './helpers'; @@ -18,6 +17,7 @@ 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}$/; @@ -34,7 +34,6 @@ test.describe('OAuth2 callback state validation', () => { test.describe.configure({ timeout: 60_000 }); test('authorization code: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { - const USER_STATE = 'brunoUserState'; const { app, page } = await startOAuth2Flow(restartApp, 'AuthCodeUserSuppliedState'); const authUrl = await getCapturedAuthUrl(app); @@ -52,18 +51,9 @@ test.describe('OAuth2 callback state validation', () => { const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; - await test.step('deliver a callback with the matching state', async () => { - await fireDeepLinkCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); - expect(returnedState).toBe(issuedState); - expect(code).toBe(authCode); - }); - - await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + expect(await readFetchedAccessToken(page)).toBeTruthy(); }); test('authorization code: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { @@ -84,43 +74,21 @@ test.describe('OAuth2 callback state validation', () => { const callbackUrl = `${CALLBACK_URL}?code=${authCode}&state=${encodeURIComponent(issuedState)}`; - await test.step('deliver a callback with the matching state', async () => { - await fireDeepLinkCallback(app, callbackUrl); - - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); - expect(returnedState).toBe(issuedState); - expect(code).toBe(authCode); - }); + await fireDeepLinkCallback(app, callbackUrl); - await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + 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 issuedState = await getIssuedStateFromAuthorizationUrl(app); - const callbackUrl = `${CALLBACK_URL}?code=${PROVIDER_AUTH_CODE}&state=${WRONG_STATE}`; - await test.step('deliver a callback with a mismatched state', async () => { - await fireDeepLinkCallback(app, callbackUrl); - - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, code } = getCallbackParams(receivedCallbackUrl as string); - expect(returnedState).toBe(WRONG_STATE); - expect(returnedState).not.toBe(issuedState); - expect(code).toBe(PROVIDER_AUTH_CODE); - }); + await fireDeepLinkCallback(app, callbackUrl); await expectStateMismatchWithoutToken(page); }); test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { - const USER_STATE = 'brunoUserState'; const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState'); const issuedState = await test.step('capture and verify the issued state carries userState', async () => { @@ -132,18 +100,9 @@ test.describe('OAuth2 callback state validation', () => { const callbackUrl = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; - await test.step('deliver a callback with the matching state', async () => { - await fireDeepLinkCallback(app, callbackUrl); + await fireDeepLinkCallback(app, callbackUrl); - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); - expect(returnedState).toBe(issuedState); - expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); - }); - - await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + expect(await readFetchedAccessToken(page)).toBe(PROVIDER_ACCESS_TOKEN); }); test('implicit grant: (no state): issues a random state accepts matching callback', async ({ restartApp }) => { @@ -158,38 +117,17 @@ test.describe('OAuth2 callback state validation', () => { const callbackUrl = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; - await test.step('deliver a callback with the matching state', async () => { - await fireDeepLinkCallback(app, callbackUrl); - - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); - expect(returnedState).toBe(issuedState); - expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); - }); + await fireDeepLinkCallback(app, callbackUrl); - await expect(page.getByText('Token fetched successfully!')).toBeVisible({ timeout: 15_000 }); + expect(await readFetchedAccessToken(page)).toBe(PROVIDER_ACCESS_TOKEN); }); test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => { const { app, page } = await startOAuth2Flow(restartApp, 'AuthorizationImplicit'); - const issuedState = await test.step('capture the issued state', () => getIssuedStateFromAuthorizationUrl(app)); - const callbackUrl = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&state=${WRONG_STATE}`; - await test.step('deliver a callback with a mismatched state', async () => { - await fireDeepLinkCallback(app, callbackUrl); - - const receivedCallbackUrl = await getCapturedCallbackUrl(app); - expect(receivedCallbackUrl).toBe(callbackUrl); - - const { state: returnedState, access_token } = getCallbackParams(receivedCallbackUrl as string, 'hash'); - expect(returnedState).toBe(WRONG_STATE); - expect(returnedState).not.toBe(issuedState); - expect(access_token).toBe(PROVIDER_ACCESS_TOKEN); - }); + await fireDeepLinkCallback(app, callbackUrl); await expectStateMismatchWithoutToken(page); }); From 33a209fa5f007ca77a781f4568d2f1589e67f0bb Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 16 Oct 2026 15:36:12 +0530 Subject: [PATCH 15/25] feat(oauth2): add data-testid for Get Access Token button and update test locators - Introduced a data-testid attribute to the Get Access Token button for enhanced testability. - Updated test helper functions to utilize the new locator for clicking the Get Access Token button. --- e2e/pages/request/auth.ts | 3 ++- .../RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js | 1 + tests/auth/oauth2/helpers.ts | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index ede91489137..65dd9438b9e 100644 --- a/e2e/pages/request/auth.ts +++ b/e2e/pages/request/auth.ts @@ -50,7 +50,8 @@ export const buildAuthLocators = (page: Page) => ({ tokenSection: (title: string) => page.getByRole('heading', { name: title, exact: true }), copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }), noToken: () => page.getByTestId('oauth2-no-token'), - tokenValue: (title: string) => page.getByTestId(`oauth2-token-value-${title}`) + tokenValue: (title: string) => page.getByTestId(`oauth2-token-value-${title}`), + getAccessTokenBtn: () => page.getByTestId('oauth2-get-access-token'), }, modeSelector: () => page.getByTestId('auth-mode-selector'), modeLabel: () => page.getByTestId('auth-mode-label'), 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/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index ac92bf39981..b256ee48657 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -23,7 +23,7 @@ export const clickGetAccessToken = async (page: Parameters[0 await openRequest(page, COLLECTION, requestName); await selectEnvironment(page, 'Local', 'collection'); await selectRequestPaneTab(page, 'Auth'); - await page.getByRole('button', { name: 'Get Access Token' }).click(); + await buildCommonLocators(page).auth.oauth2.getAccessTokenBtn().click(); }; export const getCapturedAuthUrl = (app: ElectronApplication): Promise => From 8f40eaa87df3c42b200b2761b87e937993bf3e29 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 16 Oct 2026 15:44:00 +0530 Subject: [PATCH 16/25] refactor(oauth2): update variable exports to constants in test helpers --- tests/auth/oauth2/helpers.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index b256ee48657..b9c1f2d4982 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -3,9 +3,9 @@ import { test, expect, waitForReadyPage } from '../../../playwright'; import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; import { buildCommonLocators } from '../../utils/page/locators'; -export const COLLECTION = 'oauth2-state'; -export const KEYCLOAK_USER = 'testuser'; -export const KEYCLOAK_PASSWORD = 'testpassword'; +const COLLECTION = 'oauth2-state'; +const KEYCLOAK_USER = 'testuser'; +const KEYCLOAK_PASSWORD = 'testpassword'; const loginFormActionRegex = /action="([^"]+login-actions\/authenticate[^"]*)"/; From 01b425a3b86438d299968030914bb4b24f1bf0a3 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Mon, 19 Oct 2026 12:25:35 +0530 Subject: [PATCH 17/25] fix(oauth2): change log handling in Keycloak log collection action --- .../actions/auth/oauth2/collect-keycloak-logs/action.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml index 43293ef9d09..907a02f7d36 100644 --- a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -19,8 +19,10 @@ runs: if (( ${#logs[@]} )); then cp "${logs[@]}" keycloak-logs/ else - echo "::error::No Keycloak logs found in $RUNNER_TEMP." - exit 1 + # 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." + exit 0 fi - name: Upload Keycloak logs From cb7954ea5bd3383d799861def03ae67cad8aa321 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 13:37:53 +0530 Subject: [PATCH 18/25] fixed lint error --- e2e/pages/request/auth.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index 65dd9438b9e..14de46b2a08 100644 --- a/e2e/pages/request/auth.ts +++ b/e2e/pages/request/auth.ts @@ -51,7 +51,7 @@ export const buildAuthLocators = (page: Page) => ({ copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }), noToken: () => page.getByTestId('oauth2-no-token'), tokenValue: (title: string) => page.getByTestId(`oauth2-token-value-${title}`), - getAccessTokenBtn: () => page.getByTestId('oauth2-get-access-token'), + getAccessTokenBtn: () => page.getByTestId('oauth2-get-access-token') }, modeSelector: () => page.getByTestId('auth-mode-selector'), modeLabel: () => page.getByTestId('auth-mode-label'), From 98bade179e277687b5a19cc3bef62cdc2cc44d8e Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 15:46:03 +0530 Subject: [PATCH 19/25] test(oauth2): drive implicit grant tests through a real Keycloak login --- tests/auth/oauth2/helpers.ts | 19 +++++++++- .../oauth2/oauth2-state-validation.spec.ts | 38 +++++++++++-------- 2 files changed, 40 insertions(+), 17 deletions(-) diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index b9c1f2d4982..3ff5e4d9398 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -58,7 +58,12 @@ export const getIssuedStateFromAuthorizationUrl = async (app: ElectronApplicatio return state as string; }; -export const loginToKeycloakForAuthCode = async (authorizationUrl: string): Promise => { +/** + * 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(); @@ -90,11 +95,21 @@ export const loginToKeycloakForAuthCode = async (authorizationUrl: string): Prom const location = submission.headers.get('location'); expect(location, 'Keycloak login should redirect to the callback URL').toBeTruthy(); - const code = new URL(location as string).searchParams.get('code'); + 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) => { diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/tests/auth/oauth2/oauth2-state-validation.spec.ts index a62f8d9dce4..ac1e46e58d5 100644 --- a/tests/auth/oauth2/oauth2-state-validation.spec.ts +++ b/tests/auth/oauth2/oauth2-state-validation.spec.ts @@ -5,7 +5,9 @@ import { startOAuth2Flow, getCapturedAuthUrl, getIssuedStateFromAuthorizationUrl, - loginToKeycloakForAuthCode, + loginToKeycloak, + getAuthCodeFromCallbackUrl, + getAccessTokenFromCallbackUrl, fireDeepLinkCallback, readFetchedAccessToken, expectStateMismatchWithoutToken @@ -46,8 +48,8 @@ test.describe('OAuth2 callback state validation', () => { return state; }); - const authCode = await test.step('obtain a valid auth code from Keycloak', () => - loginToKeycloakForAuthCode(authUrl as string)); + 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)}`; @@ -69,8 +71,8 @@ test.describe('OAuth2 callback state validation', () => { return state; }); - const authCode = await test.step('obtain a valid auth code from Keycloak', () => - loginToKeycloakForAuthCode(authUrl as string)); + 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)}`; @@ -91,35 +93,41 @@ test.describe('OAuth2 callback state validation', () => { test('implicit grant: (user-supplied state): issues userState accepts matching callback', async ({ restartApp }) => { const { app, page } = await startOAuth2Flow(restartApp, 'ImplicitUserSuppliedState'); - const issuedState = await test.step('capture and verify the issued state carries userState', async () => { + 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); - return state; }); - const callbackUrl - = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + const callbackUrl = await test.step('obtain a token callback from Keycloak', () => + loginToKeycloak(authUrl as string)); await fireDeepLinkCallback(app, callbackUrl); - expect(await readFetchedAccessToken(page)).toBe(PROVIDER_ACCESS_TOKEN); + 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 issuedState = await test.step('capture and verify a cryptographically random state was issued', async () => { + 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); - return state; }); - const callbackUrl - = `${CALLBACK_URL}#access_token=${PROVIDER_ACCESS_TOKEN}&token_type=Bearer&expires_in=3600&state=${encodeURIComponent(issuedState)}`; + const callbackUrl = await test.step('obtain a token callback from Keycloak', () => + loginToKeycloak(authUrl as string)); await fireDeepLinkCallback(app, callbackUrl); - expect(await readFetchedAccessToken(page)).toBe(PROVIDER_ACCESS_TOKEN); + expect(await readFetchedAccessToken(page)).toBe(getAccessTokenFromCallbackUrl(callbackUrl)); }); test('implicit grant: rejects callback when returned state does not match issued state', async ({ restartApp }) => { From c4eec2984f81c949d4560b8e597b74122b4f9400 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 15:57:02 +0530 Subject: [PATCH 20/25] ci(oauth2): kill the Keycloak process tree on Windows --- .../auth/oauth2/run-oauth2-e2e-tests/action.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml index 0838060e4e7..4a0956eb107 100644 --- a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -36,7 +36,15 @@ runs: "${kc_bin}" start-dev --http-port="${KEYCLOAK_PORT}" --import-realm > "${log}" 2>&1 & kc_pid=$! - trap 'kill "${kc_pid}" 2>/dev/null || true' EXIT + # 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 From 579485e9c0b640932dfcdb36b947fa3728076e06 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 16:12:33 +0530 Subject: [PATCH 21/25] ci(oauth2): drop the unused port input from run-oauth2-e2e-tests --- .github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml index 4a0956eb107..cccd2bb4e4b 100644 --- a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -2,10 +2,6 @@ name: 'Run OAuth2 E2E Tests' description: 'Start Keycloak and run the OAuth2 (Keycloak) E2E tests on Linux, macOS and Windows' inputs: - port: - description: 'HTTP port Keycloak listens on' - required: false - default: '8090' artifact-suffix: description: 'Suffix for the uploaded Playwright report artifact name (linux, macos, windows)' required: true @@ -18,7 +14,7 @@ runs: - name: Start Keycloak and run OAuth2 E2E tests shell: bash env: - KEYCLOAK_PORT: ${{ inputs.port }} + KEYCLOAK_PORT: '8090' run: | set -euo pipefail From 1d25b48dca72b3cd7bbbe5db3cdb80354bcdaf4f Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 16:14:33 +0530 Subject: [PATCH 22/25] chore(oauth2): restore the state rationale at the auth-code call site --- packages/bruno-electron/src/utils/oauth2.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js index 6d6fa9d82f1..84274a7510e 100644 --- a/packages/bruno-electron/src/utils/oauth2.js +++ b/packages/bruno-electron/src/utils/oauth2.js @@ -308,7 +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; - + // 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); From 9ce5cc34f2877d14783c7c9b44b30953a9371a44 Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Tue, 3 Nov 2026 16:28:12 +0530 Subject: [PATCH 23/25] resolved review comments --- .../auth/oauth2/run-oauth2-e2e-tests/action.yml | 4 ++-- .github/actions/auth/oauth2/setup-keycloak/action.yml | 2 -- e2e/pages/request/auth.ts | 2 +- .../Auth/OAuth2/Oauth2TokenViewer/index.js | 11 +++++------ tests/auth/oauth2/helpers.ts | 2 +- 5 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml index cccd2bb4e4b..1c742480b51 100644 --- a/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml +++ b/.github/actions/auth/oauth2/run-oauth2-e2e-tests/action.yml @@ -9,8 +9,8 @@ inputs: runs: using: 'composite' steps: - # Keycloak is started here and tests run in same step due cause Github Actions kills a child-process - # when the step ends. KC_HOME comes from the setup-keycloak step. + # 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: diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index 95ab0cb81b1..cf70ba7c5e8 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -15,8 +15,6 @@ runs: with: distribution: temurin java-version: '21' - # NOTE: On Windows, GitHub Actions terminates child process tree when the step completes. - # So keycloak is started in the same step where tests are ran. - name: Download and prepare Keycloak shell: bash working-directory: ${{ runner.temp }} diff --git a/e2e/pages/request/auth.ts b/e2e/pages/request/auth.ts index 14de46b2a08..961c6d564c5 100644 --- a/e2e/pages/request/auth.ts +++ b/e2e/pages/request/auth.ts @@ -50,7 +50,7 @@ export const buildAuthLocators = (page: Page) => ({ tokenSection: (title: string) => page.getByRole('heading', { name: title, exact: true }), copyTokenButton: () => page.getByRole('button', { name: 'Copy token' }), noToken: () => page.getByTestId('oauth2-no-token'), - tokenValue: (title: string) => page.getByTestId(`oauth2-token-value-${title}`), + 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'), 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 503c1578852..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); @@ -36,7 +36,6 @@ const TokenSection = ({ title, token }) => {
setIsExpanded(!isExpanded)} >
@@ -63,7 +62,7 @@ const TokenSection = ({ title, token }) => { : }
-
+
{token}
@@ -141,9 +140,9 @@ const Oauth2TokenViewer = ({ collection, item, url, credentialsId, handleRun })
Error fetching token. Check network logs for more details.
) : (
- - - + + + {(creds.token_type || creds.scope) ? (
diff --git a/tests/auth/oauth2/helpers.ts b/tests/auth/oauth2/helpers.ts index 3ff5e4d9398..149105793db 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/tests/auth/oauth2/helpers.ts @@ -121,7 +121,7 @@ export const readFetchedAccessToken = async (page: Parameters Date: Tue, 3 Nov 2026 16:37:26 +0530 Subject: [PATCH 24/25] ci(oauth2): tidy the log-staging script and add missing trailing newlines --- .github/actions/auth/oauth2/collect-keycloak-logs/action.yml | 3 +-- .github/workflows/tests-linux.yml | 2 +- .github/workflows/tests-macos.yml | 2 +- tests/auth/oauth2/fixtures/keycloak/realm-export.json | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml index 907a02f7d36..c90af24c32b 100644 --- a/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml +++ b/.github/actions/auth/oauth2/collect-keycloak-logs/action.yml @@ -12,7 +12,7 @@ runs: - name: Stage Keycloak logs shell: bash run: | - set -uo pipefail + set -euo pipefail mkdir -p keycloak-logs shopt -s nullglob logs=("$RUNNER_TEMP"/keycloak*.log) @@ -22,7 +22,6 @@ runs: # 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." - exit 0 fi - name: Upload Keycloak logs diff --git a/.github/workflows/tests-linux.yml b/.github/workflows/tests-linux.yml index e0c3469839c..21c1f42b30f 100644 --- a/.github/workflows/tests-linux.yml +++ b/.github/workflows/tests-linux.yml @@ -260,4 +260,4 @@ jobs: if: ${{ !cancelled() }} uses: ./.github/actions/auth/oauth2/collect-keycloak-logs with: - artifact-suffix: linux \ No newline at end of file + artifact-suffix: linux diff --git a/.github/workflows/tests-macos.yml b/.github/workflows/tests-macos.yml index f60f159230f..95f230d2d9e 100644 --- a/.github/workflows/tests-macos.yml +++ b/.github/workflows/tests-macos.yml @@ -189,4 +189,4 @@ jobs: if: ${{ !cancelled() }} uses: ./.github/actions/auth/oauth2/collect-keycloak-logs with: - artifact-suffix: macos \ No newline at end of file + artifact-suffix: macos diff --git a/tests/auth/oauth2/fixtures/keycloak/realm-export.json b/tests/auth/oauth2/fixtures/keycloak/realm-export.json index 79fce74dd2f..e14d0b39ed4 100644 --- a/tests/auth/oauth2/fixtures/keycloak/realm-export.json +++ b/tests/auth/oauth2/fixtures/keycloak/realm-export.json @@ -50,4 +50,4 @@ ] } ] -} \ No newline at end of file +} From 7325bb9c45392c418b62bf08e1342eb31a81721d Mon Sep 17 00:00:00 2001 From: abhishekp-bruno Date: Fri, 20 Nov 2026 17:42:14 +0530 Subject: [PATCH 25/25] moved to e2e folder and fixed imports --- .github/actions/auth/oauth2/setup-keycloak/action.yml | 2 +- {tests => e2e/tests}/auth/oauth2/README.md | 2 +- .../oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml | 0 .../auth/oauth2/fixtures/collection/AuthorizationCode.yml | 0 .../auth/oauth2/fixtures/collection/AuthorizationImplicit.yml | 0 .../oauth2/fixtures/collection/ImplicitUserSuppliedState.yml | 0 .../tests}/auth/oauth2/fixtures/collection/bruno.json | 0 .../auth/oauth2/fixtures/collection/environments/Local.yml | 0 .../tests}/auth/oauth2/fixtures/collection/opencollection.yml | 0 .../tests}/auth/oauth2/fixtures/keycloak/realm-export.json | 0 {tests => e2e/tests}/auth/oauth2/helpers.ts | 3 +-- .../tests}/auth/oauth2/init-user-data/preferences.json | 0 .../tests}/auth/oauth2/oauth2-state-validation.spec.ts | 0 13 files changed, 3 insertions(+), 4 deletions(-) rename {tests => e2e/tests}/auth/oauth2/README.md (88%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/AuthorizationCode.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/bruno.json (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/environments/Local.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/collection/opencollection.yml (100%) rename {tests => e2e/tests}/auth/oauth2/fixtures/keycloak/realm-export.json (100%) rename {tests => e2e/tests}/auth/oauth2/helpers.ts (97%) rename {tests => e2e/tests}/auth/oauth2/init-user-data/preferences.json (100%) rename {tests => e2e/tests}/auth/oauth2/oauth2-state-validation.spec.ts (100%) diff --git a/.github/actions/auth/oauth2/setup-keycloak/action.yml b/.github/actions/auth/oauth2/setup-keycloak/action.yml index cf70ba7c5e8..98ade99ca23 100644 --- a/.github/actions/auth/oauth2/setup-keycloak/action.yml +++ b/.github/actions/auth/oauth2/setup-keycloak/action.yml @@ -29,7 +29,7 @@ runs: KC_HOME="${RUNNER_TEMP}/keycloak-${KEYCLOAK_VERSION}" mkdir -p "${KC_HOME}/data/import" - cp "${GITHUB_WORKSPACE}/tests/auth/oauth2/fixtures/keycloak/realm-export.json" \ + 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}" diff --git a/tests/auth/oauth2/README.md b/e2e/tests/auth/oauth2/README.md similarity index 88% rename from tests/auth/oauth2/README.md rename to e2e/tests/auth/oauth2/README.md index 21b039abe02..25e269ca2c9 100644 --- a/tests/auth/oauth2/README.md +++ b/e2e/tests/auth/oauth2/README.md @@ -17,7 +17,7 @@ Start Keycloak with the fixture realm imported: ```bash docker run -d --name bruno-keycloak -p 8090:8080 \ - -v "$PWD/tests/auth/oauth2/fixtures/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro" \ + -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 ``` diff --git a/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml rename to e2e/tests/auth/oauth2/fixtures/collection/AuthCodeUserSuppliedState.yml diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml rename to e2e/tests/auth/oauth2/fixtures/collection/AuthorizationCode.yml diff --git a/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml b/e2e/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml rename to e2e/tests/auth/oauth2/fixtures/collection/AuthorizationImplicit.yml diff --git a/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml b/e2e/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml rename to e2e/tests/auth/oauth2/fixtures/collection/ImplicitUserSuppliedState.yml diff --git a/tests/auth/oauth2/fixtures/collection/bruno.json b/e2e/tests/auth/oauth2/fixtures/collection/bruno.json similarity index 100% rename from tests/auth/oauth2/fixtures/collection/bruno.json rename to e2e/tests/auth/oauth2/fixtures/collection/bruno.json diff --git a/tests/auth/oauth2/fixtures/collection/environments/Local.yml b/e2e/tests/auth/oauth2/fixtures/collection/environments/Local.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/environments/Local.yml rename to e2e/tests/auth/oauth2/fixtures/collection/environments/Local.yml diff --git a/tests/auth/oauth2/fixtures/collection/opencollection.yml b/e2e/tests/auth/oauth2/fixtures/collection/opencollection.yml similarity index 100% rename from tests/auth/oauth2/fixtures/collection/opencollection.yml rename to e2e/tests/auth/oauth2/fixtures/collection/opencollection.yml diff --git a/tests/auth/oauth2/fixtures/keycloak/realm-export.json b/e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json similarity index 100% rename from tests/auth/oauth2/fixtures/keycloak/realm-export.json rename to e2e/tests/auth/oauth2/fixtures/keycloak/realm-export.json diff --git a/tests/auth/oauth2/helpers.ts b/e2e/tests/auth/oauth2/helpers.ts similarity index 97% rename from tests/auth/oauth2/helpers.ts rename to e2e/tests/auth/oauth2/helpers.ts index 149105793db..e8f5d308f82 100644 --- a/tests/auth/oauth2/helpers.ts +++ b/e2e/tests/auth/oauth2/helpers.ts @@ -1,7 +1,6 @@ import type { ElectronApplication } from 'playwright'; import { test, expect, waitForReadyPage } from '../../../playwright'; -import { openRequest, selectRequestPaneTab, selectEnvironment } from '../../utils/page'; -import { buildCommonLocators } from '../../utils/page/locators'; +import { openRequest, selectRequestPaneTab, selectEnvironment, buildCommonLocators } from '../../../pages'; const COLLECTION = 'oauth2-state'; const KEYCLOAK_USER = 'testuser'; diff --git a/tests/auth/oauth2/init-user-data/preferences.json b/e2e/tests/auth/oauth2/init-user-data/preferences.json similarity index 100% rename from tests/auth/oauth2/init-user-data/preferences.json rename to e2e/tests/auth/oauth2/init-user-data/preferences.json diff --git a/tests/auth/oauth2/oauth2-state-validation.spec.ts b/e2e/tests/auth/oauth2/oauth2-state-validation.spec.ts similarity index 100% rename from tests/auth/oauth2/oauth2-state-validation.spec.ts rename to e2e/tests/auth/oauth2/oauth2-state-validation.spec.ts