[PR #5575] feat: auto oauth2 token generation for collection runner and cli #5264

Open
opened 2026-03-17 02:43:39 +03:00 by kerem · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/hoppscotch/hoppscotch/pull/5575
Author: @Leon-Luu
Created: 11/12/2025
Status: 🔄 Open

Base: mainHead: feat/auto_oath2_on_collection_run


📝 Commits (10+)

  • 76ebaeb feat: add auto oath2.0 generate from collection runner
  • 614d62d fix: toast reference
  • de43709 chore: add test for auto oauth2 runner
  • 9fba217 feat: add cli support for outh2 colection level token generator
  • 0381829 chore: fix copilot reviews
  • 66a9ce1 fix: populate env variables correctly to the cli collection run
  • cdfe93f fix: improve OAuth auto-token-generator type safety
  • 1d6b52c feat: re-factor with unifying cli and ui to use same oauth generators
  • 0208a83 fix: resolve test runner OAuth issues for team workspace collections
  • 152755f feat: add auto oath2.0 generate from collection runner

📊 Changes

15 files changed (+2112 additions, -38 deletions)

View changed files

📝 packages/hoppscotch-cli/src/__tests__/e2e/commands/__snapshots__/test.spec.ts.snap (+4 -4)
📝 packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.ts (+1 -1)
packages/hoppscotch-cli/src/__tests__/unit/oauth/token-generator.spec.ts (+490 -0)
📝 packages/hoppscotch-cli/src/utils/collections.ts (+81 -2)
packages/hoppscotch-cli/src/utils/oauth/token-generator.ts (+336 -0)
📝 packages/hoppscotch-cli/src/utils/workspace-access.ts (+19 -12)
📝 packages/hoppscotch-common/locales/en.json (+5 -1)
📝 packages/hoppscotch-common/src/components/http/test/Runner.vue (+47 -10)
packages/hoppscotch-common/src/helpers/oauth/auto-token-generator.ts (+184 -0)
📝 packages/hoppscotch-common/src/services/oauth/flows/password.ts (+6 -3)
packages/hoppscotch-common/src/services/test-runner/__tests__/test-runner-oauth.spec.ts (+688 -0)
📝 packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts (+67 -4)
📝 packages/hoppscotch-data/src/environment/index.ts (+2 -1)
📝 packages/hoppscotch-data/src/index.ts (+1 -0)
packages/hoppscotch-data/src/utils/oauth.ts (+181 -0)

📄 Description

This implementation adds automatic OAuth 2.0 token generation at the start of collection runs in Hoppscotch. The feature eliminates the need for manual token generation before running collections, streamlining the workflow and improving reliability. Implements automatic OAuth token generation for CLI collections, matching UI runner functionality.

Before This Feature

  1. Right-click Collection → Properties
  2. Go to Authorization tab
  3. Configure OAuth settings
  4. Click "Generate Token"
  5. Wait for OAuth flow
  6. Close Properties
  7. Right-click Collection → Run Collection
  8. Configure run settings
  9. Click Run

After This Feature

  1. Right-click Collection → Run Collection
  2. Configure run settings (OAuth config already in collection)
  3. Click Run
  4. (Token auto-generated in background)

Benefits

1. Streamlined Workflow

  • Before: Open Collection Properties → Generate Token → Go back → Run Collection
  • After: Run Collection (token auto-generated)

2. Consistency

  • All requests in the collection use the same fresh token
  • Eliminates token expiration issues during long-running collections

3. Reliability

  • Reduces authentication failures due to forgotten or expired tokens
  • Fresh token generated every time

4. Automation-Ready

  • Perfect for CI/CD pipelines
  • No manual intervention needed for supported grant types

Supported Grant Types (Automatic Generation)

  1. Client Credentials

    • Fully automatic
    • No user interaction required
    • Ideal for server-to-server authentication
  2. Password (Resource Owner Password Credentials)

    • Fully automatic
    • Requires username/password configured in collection
    • Useful for testing environments

⚠️ Not Supported (Requires Manual Token Generation)

  1. Authorization Code

    • Requires browser redirect
    • User must generate token manually via Collection Properties
  2. Implicit

    • Requires browser redirect
    • User must generate token manually via Collection Properties

Closes #
https://github.com/hoppscotch/hoppscotch/issues/5478

Implementation Flow (UI collection runner)

User Clicks "Run Collection"
    ↓
Collection Runner Modal Opens
    ↓
User Configures Run Settings
    ↓
User Clicks "Run"
    ↓
TestRunnerService.runTests() Called
    ↓
Check if Collection has OAuth 2.0?
    ├─ NO → Continue to run collection normally
    └─ YES → Continue to OAuth check
          ↓
          Check Grant Type
          ├─ Redirect Type (Auth Code/Implicit) → Show error, stop execution
          └─ Supported Type (Client Creds/Password) → Continue
                ↓
                Call generateOAuth2TokenForCollection() (Silent)
                ↓
                Token Generation Success?
                ├─ NO → Show error toast, stop execution
                └─ YES → Continue
                      ↓
                      Update collection with token
                      ↓
                      Show success toast: "Token fetched successfully"
                      ↓
                      Run collection with token
                      ↓
                      All requests inherit the token
                      ↓
                      Collection execution completes

Implementation Flow (CLI mode)

collectionsRunner() called
  ↓
Loop through collections
  ↓
For each collection:
  - Check hasOAuth2Auth()
  - Validate grant type (no redirects)
  - Generate token
  - Update collection
  ↓
Process requests (existing flow)

Technical Details

Token Generation Process

  1. Validation: Check grant type and validate required fields
  2. Template String Replacement: Replace environment variables in OAuth config
  3. Parameter Validation: Validate using Zod schemas from flow implementations
  4. HTTP Request: Make token request to OAuth server
  5. Response Parsing: Parse and validate token response
  6. Token Storage: Update collection auth configuration with token
  7. Token Propagation: Token inherited by all child requests

Error Handling

The implementation provides specific error messages for:

  • Missing OAuth configuration (no_config_found)
  • Unsupported grant types for auto-generation (redirect_not_supported_for_collection)
  • Validation failures (auto_generation_validation_failed)
  • Token generation failures (token_fetch_failed)
  • Unsupported grant types (unsupported_grant_type_for_auto_generation)

Each error displays a user-friendly toast message and stops collection execution.

What's changed

  1. packages/hoppscotch-common/src/helpers/oauth/auto-token-generator.ts
    • Core logic for automatic OAuth 2.0 token generation
    • Supports Client Credentials and Password grant types
    • Exports helper functions:
      • hasOAuth2Auth() - Checks if collection has OAuth configured
      • requiresRedirect() - Checks if grant type needs browser redirect
      • generateOAuth2TokenForCollection() - Main function to generate tokens
      • updateCollectionWithToken() - Updates collection with generated token

Notes to reviewers

  1. Manual test with UI run collection, "Run again" and "New run" validated
  2. Manual CLI mode test has been done (CLI mode with collection.json file, CLI mode with PAT/collection-id, env with secrets and server mode)
  3. Created unit and integration testing and passed for UI and CLI mode

Summary by cubic

Automatically generates OAuth 2.0 tokens at the start of collection runs in both UI and CLI. Removes manual token steps and improves reliability for long runs and CI.

  • New Features

    • UI Collection Runner auto-generates tokens when OAuth 2.0 is active on the collection.
    • CLI Collections Runner generates tokens before requests and aborts on redirect grant types with clear errors.
    • Supports Client Credentials and Password grants with localized toasts/messages.
    • Writes the token back to the collection so all child requests inherit it.
    • Stores refresh token for Password grant when available.
    • CLI resolves secret env variables from the system environment and expands OAuth config before token requests.
    • UI runner refetches the latest collection and preserves OAuth auth in team workspaces to avoid inheritance overrides.
    • UI runner updates both the original and result collections with the generated token.
    • Added unit and integration tests for UI and CLI runners.
    • Shared OAuth utilities unify UI and CLI behavior; expands tokenRequestParams with env variables and validates token responses consistently.
    • Security hardening: safer env variable parsing to prevent ReDoS in template expansion.
  • Migration

    • Ensure OAuth settings are saved on the collection; no manual token needed for supported grants.
    • Authorization Code and Implicit are not auto-generated. Generate tokens manually; CLI exits early on these.

Written for commit 56cfd314cf. Summary will update automatically on new commits.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/hoppscotch/hoppscotch/pull/5575 **Author:** [@Leon-Luu](https://github.com/Leon-Luu) **Created:** 11/12/2025 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/auto_oath2_on_collection_run` --- ### 📝 Commits (10+) - [`76ebaeb`](https://github.com/hoppscotch/hoppscotch/commit/76ebaeb31d5c3123e840cd3fa337455b15529320) feat: add auto oath2.0 generate from collection runner - [`614d62d`](https://github.com/hoppscotch/hoppscotch/commit/614d62d0ff9f23c2ee64d9e9cc61abd8497513fe) fix: toast reference - [`de43709`](https://github.com/hoppscotch/hoppscotch/commit/de4370974e17440d4157079ed56150cfaf666d4b) chore: add test for auto oauth2 runner - [`9fba217`](https://github.com/hoppscotch/hoppscotch/commit/9fba21769722827bb7a5d22ab1643b52cbc413eb) feat: add cli support for outh2 colection level token generator - [`0381829`](https://github.com/hoppscotch/hoppscotch/commit/03818294a5c31cec9043c2c0a5c13227dccb7174) chore: fix copilot reviews - [`66a9ce1`](https://github.com/hoppscotch/hoppscotch/commit/66a9ce1421de33dc3552ef6053ca1e125355de65) fix: populate env variables correctly to the cli collection run - [`cdfe93f`](https://github.com/hoppscotch/hoppscotch/commit/cdfe93fc7cf3e5fd8f92b6c812650a2514fa0749) fix: improve OAuth auto-token-generator type safety - [`1d6b52c`](https://github.com/hoppscotch/hoppscotch/commit/1d6b52ca6aa341094f9ae68bce43123df20e5926) feat: re-factor with unifying cli and ui to use same oauth generators - [`0208a83`](https://github.com/hoppscotch/hoppscotch/commit/0208a83942e9ce1c7bba18edfefa380292d50c15) fix: resolve test runner OAuth issues for team workspace collections - [`152755f`](https://github.com/hoppscotch/hoppscotch/commit/152755f40dd71dff0a3da75d8949e29a14043584) feat: add auto oath2.0 generate from collection runner ### 📊 Changes **15 files changed** (+2112 additions, -38 deletions) <details> <summary>View changed files</summary> 📝 `packages/hoppscotch-cli/src/__tests__/e2e/commands/__snapshots__/test.spec.ts.snap` (+4 -4) 📝 `packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.ts` (+1 -1) ➕ `packages/hoppscotch-cli/src/__tests__/unit/oauth/token-generator.spec.ts` (+490 -0) 📝 `packages/hoppscotch-cli/src/utils/collections.ts` (+81 -2) ➕ `packages/hoppscotch-cli/src/utils/oauth/token-generator.ts` (+336 -0) 📝 `packages/hoppscotch-cli/src/utils/workspace-access.ts` (+19 -12) 📝 `packages/hoppscotch-common/locales/en.json` (+5 -1) 📝 `packages/hoppscotch-common/src/components/http/test/Runner.vue` (+47 -10) ➕ `packages/hoppscotch-common/src/helpers/oauth/auto-token-generator.ts` (+184 -0) 📝 `packages/hoppscotch-common/src/services/oauth/flows/password.ts` (+6 -3) ➕ `packages/hoppscotch-common/src/services/test-runner/__tests__/test-runner-oauth.spec.ts` (+688 -0) 📝 `packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts` (+67 -4) 📝 `packages/hoppscotch-data/src/environment/index.ts` (+2 -1) 📝 `packages/hoppscotch-data/src/index.ts` (+1 -0) ➕ `packages/hoppscotch-data/src/utils/oauth.ts` (+181 -0) </details> ### 📄 Description <!-- Thanks for creating this pull request 🤗 Please make sure that the pull request is limited to one type (docs, feature, etc.) and keep it as small as possible. You can open multiple prs instead of opening a huge one. --> This implementation adds automatic OAuth 2.0 token generation at the start of collection runs in Hoppscotch. The feature eliminates the need for manual token generation before running collections, streamlining the workflow and improving reliability. Implements automatic OAuth token generation for CLI collections, matching UI runner functionality. ### Before This Feature 1. Right-click Collection → Properties 2. Go to Authorization tab 3. Configure OAuth settings 4. Click "Generate Token" 5. Wait for OAuth flow 6. Close Properties 7. Right-click Collection → Run Collection 8. Configure run settings 9. Click Run ### After This Feature 1. Right-click Collection → Run Collection 2. Configure run settings (OAuth config already in collection) 3. Click Run 4. (Token auto-generated in background) ## Benefits ### 1. Streamlined Workflow - **Before**: Open Collection Properties → Generate Token → Go back → Run Collection - **After**: Run Collection (token auto-generated) ### 2. Consistency - All requests in the collection use the same fresh token - Eliminates token expiration issues during long-running collections ### 3. Reliability - Reduces authentication failures due to forgotten or expired tokens - Fresh token generated every time ### 4. Automation-Ready - Perfect for CI/CD pipelines - No manual intervention needed for supported grant types ### ✅ Supported Grant Types (Automatic Generation) 1. **Client Credentials** - Fully automatic - No user interaction required - Ideal for server-to-server authentication 2. **Password (Resource Owner Password Credentials)** - Fully automatic - Requires username/password configured in collection - Useful for testing environments ### ⚠️ Not Supported (Requires Manual Token Generation) 1. **Authorization Code** - Requires browser redirect - User must generate token manually via Collection Properties 2. **Implicit** - Requires browser redirect - User must generate token manually via Collection Properties <!-- If this pull request closes an issue, please mention the issue number below --> Closes # <!-- Issue # here --> https://github.com/hoppscotch/hoppscotch/issues/5478 ## Implementation Flow (UI collection runner) ``` User Clicks "Run Collection" ↓ Collection Runner Modal Opens ↓ User Configures Run Settings ↓ User Clicks "Run" ↓ TestRunnerService.runTests() Called ↓ Check if Collection has OAuth 2.0? ├─ NO → Continue to run collection normally └─ YES → Continue to OAuth check ↓ Check Grant Type ├─ Redirect Type (Auth Code/Implicit) → Show error, stop execution └─ Supported Type (Client Creds/Password) → Continue ↓ Call generateOAuth2TokenForCollection() (Silent) ↓ Token Generation Success? ├─ NO → Show error toast, stop execution └─ YES → Continue ↓ Update collection with token ↓ Show success toast: "Token fetched successfully" ↓ Run collection with token ↓ All requests inherit the token ↓ Collection execution completes ``` ## Implementation Flow (CLI mode) ``` collectionsRunner() called ↓ Loop through collections ↓ For each collection: - Check hasOAuth2Auth() - Validate grant type (no redirects) - Generate token - Update collection ↓ Process requests (existing flow) ``` ## Technical Details ### Token Generation Process 1. **Validation**: Check grant type and validate required fields 2. **Template String Replacement**: Replace environment variables in OAuth config 3. **Parameter Validation**: Validate using Zod schemas from flow implementations 4. **HTTP Request**: Make token request to OAuth server 5. **Response Parsing**: Parse and validate token response 6. **Token Storage**: Update collection auth configuration with token 7. **Token Propagation**: Token inherited by all child requests ### Error Handling The implementation provides specific error messages for: - Missing OAuth configuration (`no_config_found`) - Unsupported grant types for auto-generation (`redirect_not_supported_for_collection`) - Validation failures (`auto_generation_validation_failed`) - Token generation failures (`token_fetch_failed`) - Unsupported grant types (`unsupported_grant_type_for_auto_generation`) Each error displays a user-friendly toast message and stops collection execution. <!-- Add an introduction into what this PR tries to solve in a couple of sentences --> ### What's changed <!-- Describe point by point the different things you have changed in this PR --> <!-- You can also choose to add a list of changes and if they have been completed or not by using the markdown to-do list syntax - [ ] Not Completed - [x] Completed --> 1. **`packages/hoppscotch-common/src/helpers/oauth/auto-token-generator.ts`** - Core logic for automatic OAuth 2.0 token generation - Supports Client Credentials and Password grant types - Exports helper functions: - `hasOAuth2Auth()` - Checks if collection has OAuth configured - `requiresRedirect()` - Checks if grant type needs browser redirect - `generateOAuth2TokenForCollection()` - Main function to generate tokens - `updateCollectionWithToken()` - Updates collection with generated token ### Notes to reviewers <!-- Any information you feel the reviewer should know about when reviewing your PR --> 1) Manual test with UI run collection, "Run again" and "New run" validated 2) Manual CLI mode test has been done (CLI mode with collection.json file, CLI mode with PAT/collection-id, env with secrets and server mode) 3) Created unit and integration testing and passed for UI and CLI mode <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Automatically generates OAuth 2.0 tokens at the start of collection runs in both UI and CLI. Removes manual token steps and improves reliability for long runs and CI. - **New Features** - UI Collection Runner auto-generates tokens when OAuth 2.0 is active on the collection. - CLI Collections Runner generates tokens before requests and aborts on redirect grant types with clear errors. - Supports Client Credentials and Password grants with localized toasts/messages. - Writes the token back to the collection so all child requests inherit it. - Stores refresh token for Password grant when available. - CLI resolves secret env variables from the system environment and expands OAuth config before token requests. - UI runner refetches the latest collection and preserves OAuth auth in team workspaces to avoid inheritance overrides. - UI runner updates both the original and result collections with the generated token. - Added unit and integration tests for UI and CLI runners. - Shared OAuth utilities unify UI and CLI behavior; expands tokenRequestParams with env variables and validates token responses consistently. - Security hardening: safer env variable parsing to prevent ReDoS in template expansion. - **Migration** - Ensure OAuth settings are saved on the collection; no manual token needed for supported grants. - Authorization Code and Implicit are not auto-generated. Generate tokens manually; CLI exits early on these. <sup>Written for commit 56cfd314cf9ef1bfaea867bde92607d90f88eb8c. Summary will update automatically on new commits.</sup> <!-- End of auto-generated description by cubic. --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/hoppscotch#5264
No description provided.