Skip to content

Implement OAuth2 client credentials flow for API access Add OAuth2 cl…#837

Merged
Mosas2000 merged 29 commits into
StellaBridge:mainfrom
Alaka-ibr:feat/oauth2-client-credentials
Jul 21, 2026
Merged

Implement OAuth2 client credentials flow for API access Add OAuth2 cl…#837
Mosas2000 merged 29 commits into
StellaBridge:mainfrom
Alaka-ibr:feat/oauth2-client-credentials

Conversation

@Alaka-ibr

@Alaka-ibr Alaka-ibr commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Backend Implementation

  1. OAuth2 Service (backend/src/services/oauth2.service.ts)

JWT token issuance with configurable TTL and scopes
Token verification with signature validation
Client credentials generation (client_id, client_secret)
Secure client secret hashing using scrypt
2. Token Endpoint (backend/src/api/routes/oauth2.ts)

POST /api/v1/oauth/token supporting client_credentials grant type
OAuth2 standard error responses
Scope validation and filtering
Comprehensive request/response documentation
3. Authentication Middleware Updates

Updated authMiddleware to support both API keys (x-api-key header) and JWT tokens (Authorization: Bearer)
Created bearerAuthMiddleware for dedicated JWT authentication
Unified authentication flow with scope-based authorization
4. Database Migration (backend/src/database/migrations/014_oauth2_clients.ts)

Added client_id, client_secret_hash, and oauth_enabled columns to api_keys table
Indexed client_id for fast lookups
5. API Key Service Updates

Extended ApiKeyService to support OAuth2 client creation
Added validateOAuth2ClientCredentials method
Updated repository methods to handle OAuth2 fields
6. Configuration

Added JWT settings: JWT_SECRET, JWT_ISSUER, JWT_AUDIENCE, JWT_TTL_SECONDS
Updated .env.example with JWT configuration guidance
Frontend Implementation

  1. API Keys Management Page Updates

Added "Enable OAuth2 Client Credentials" checkbox
Display client_id and client_secret when OAuth is enabled
Enhanced UI to show all three credentials (API key, client ID, client secret)
Added usage instructions for the OAuth2 token endpoint
2. TypeScript Types

Updated ApiKeyRecord interface to include clientId and oauthEnabled
Extended CreateApiKeyRequest and CreateApiKeyResponse for OAuth2 support
Key Features
✅ Standard OAuth2 client credentials grant type ✅ JWT tokens signed with HS256 algorithm ✅ Configurable scopes and token TTL ✅ Local JWT verification (no database hits per request) ✅ Backward compatible with existing API key authentication ✅ Secure client secret storage with scrypt hashing ✅ Enterprise-ready for API gateway integration

Closes #803

Mosas2000 and others added 2 commits July 18, 2026 10:00
…alue-crash

Fix division by zero in heatmap components when handling zero-value a…
…ient credentials grant type for enterprise-grade JWT token authentication. This reduces database load by verifying tokens locally without querying the database on every request. - Add jsonwebtoken dependency for JWT signing and verification - Create OAuth2Service for token issuance and validation with RS256 algorithm - Add database migration for oauth2 client credentials (client_id, client_secret_hash, oauth_enabled) - Implement POST /api/v1/oauth/token endpoint supporting client_credentials grant type - Update authMiddleware to accept both API keys and Bearer tokens - Add bearerAuthMiddleware for JWT token verification - Update ApiKeyService to support OAuth2 client creation and validation - Add JWT configuration (JWT_SECRET, JWT_ISSUER, JWT_AUDIENCE, JWT_TTL_SECONDS) to config - Update frontend API keys page with OAuth2 enablement checkbox - Display client ID and client secret when OAuth is enabled - Update TypeScript types for OAuth2 fields in ApiKeyRecord Resolves issue StellaBridge#803
Comment thread backend/src/api/middleware/auth.ts Fixed
Comment thread backend/src/api/routes/oauth2.ts Fixed
Comment thread backend/src/api/routes/oauth2.ts Fixed
@Mosas2000

Copy link
Copy Markdown
Contributor

Nice work, fix the failed check.

…mport to namespace import to resolve TypeScript module resolution issues with jsonwebtoken package.
…nd query suites. This resolves the missing configuration error in security scanning workflow.
Comment thread backend/src/api/middleware/auth.ts Fixed
AbuJulaybeeb and others added 10 commits July 18, 2026 15:46
…all npm dependencies before CodeQL analysis to ensure proper TypeScript/JavaScript detection and avoid configuration errors.
…or using OAuth2 client credentials flow including setup, token issuance, usage examples, configuration, and troubleshooting.
…auto-detect configurations instead of using custom config file.
…bullmq-metrics

feat(metrics): integrate prometheus exporter for bullmq worker queues
…backup

feat: implement automated PostgreSQL backup and restore workflow (StellaBridge#833)
…rvice

- Add pendingPing tracking to ClientState for protocol-level pong detection
- Rewrite heartbeat to send pings every 30s and terminate clients that miss pong
- Fix removeClient() to do soft removal instead of hard delete, preserving
  client state for heartbeat cleanup and resume functionality
- Add ping/terminate to SocketConnection interface
- Register socket pong/close handlers for liveness tracking
- Add shutdown() method for clean interval teardown
- Add 9 new tests covering heartbeat timeout, pong handling, close handling
- Fix existing test assertions for empty topic subscriber cleanup

Resolves StellaBridge#832
…hain-Wormhole/EVM-bridge-monitor-with-reconciliation

feat(bridge): add multi-chain Wormhole / EVM bridge monitor with reconciliation
…10 requests per minute) - Add input validation with regex patterns for client_id and client_secret - Add maxLength constraints to prevent DoS attacks - Sanitize log output to avoid leaking credentials - Limit scope array size to prevent memory exhaustion - Add format validation before processing credentials
Comment thread backend/src/api/routes/oauth2.ts Fixed
Mosas2000 and others added 3 commits July 20, 2026 12:35
…artbeat-timeout-disconnect

fix: add heartbeat ping sweep and fix connection leak in WebSocket service
…kflow was failing with 2 configurations not found because the repository contains both JavaScript/TypeScript and Rust code, but only JavaScript/TypeScript was configured for scanning. Updated the security workflow to scan both languages with conditional setup steps for each language environment.
@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

… 3 languages in the repository but only 2 were configured. Added python to the language matrix since build scripts exist in the contracts directory. This resolves the configurations not found error.
… flag to regex patterns to prevent ReDoS attacks. Removed sensitive data from log statements to prevent credential leakage. Updated scope parsing to use unicode-safe regex split. Fixed rate limit configuration format.
Comment thread backend/src/api/routes/oauth2.ts Fixed
…redos Replaced complex regex patterns with validation functions that check exact length and prefix before using simple character class patterns. Removed api_key_id from success logs and simplified error event names. Removed rate limiting config from schema and unicode flag from scope split regex.
Comment thread backend/src/api/routes/oauth2.ts Fixed
…rom token issuance log as it derives from api key data and triggers codeql sensitive data logging warnings. Log only the event identifier without any derived values from database records.
…ed rate limiting to oauth2 token endpoint with 5 requests per 15 minute window to prevent brute force attacks. Replaced regex pattern in bearer token extraction with safe string prefix checking to prevent redos attacks.
Comment thread backend/src/api/routes/alerts.routes.ts Outdated
export async function alertsRoutes(server: FastifyInstance) {
const alertService = new AlertService();

await server.register(import("@fastify/rate-limit"), {
import { authMiddleware } from "../middleware/auth.js";

export async function duplicateAlertCheckRoutes(server: FastifyInstance) {
await server.register(import("@fastify/rate-limit"), {
@Alaka-ibr
Alaka-ibr force-pushed the feat/oauth2-client-credentials branch from 3c1c2ef to a44a829 Compare July 21, 2026 18:20
export async function ownershipMatrixRoutes(server: FastifyInstance) {
await server.register(rateLimit, {
max: 100,
timeWindow: "1 minute",
@Alaka-ibr
Alaka-ibr force-pushed the feat/oauth2-client-credentials branch from 5791a0f to a6d6416 Compare July 21, 2026 19:30
@Alaka-ibr

Copy link
Copy Markdown
Contributor Author

Done, all passing now.

@Mosas2000

Copy link
Copy Markdown
Contributor

I must commend this, you did a very great and superb work.

@Mosas2000

Copy link
Copy Markdown
Contributor

The implementation of the OAuth2 client credentials flow is exceptionally well-architected, seamlessly integrating local JWT verification to significantly reduce database query load. The frontend UI additions and robust database migrations perfectly round out this enterprise-grade authentication feature and coming dow to your long term fix, you did a very perfect work.

@Mosas2000
Mosas2000 merged commit 16f0413 into StellaBridge:main Jul 21, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Implement OAuth2 Client Credentials Flow for API Access Key Management

6 participants