Skip to content

Conversation

@lukesmmr
Copy link
Member

@lukesmmr lukesmmr commented Feb 8, 2026

Protect /api and /graphql routes with Bearer token auth using timing-safe comparison. Health, metrics, and docs endpoints remain open. Auth is skipped in test environment. API_KEY is required in production via Joi env validation.

Summary by CodeRabbit

  • New Features

    • Implemented API key authentication using Bearer tokens in the Authorization header for all API endpoints.
    • API key is required in production environments and optional in development/test environments.
  • Tests

    • Added comprehensive test coverage for authentication middleware.
  • Chores

    • Updated environment configuration documentation with API authentication setup guidance.
    • Updated API specification to reflect Bearer token authentication method.

Protect /api and /graphql routes with Bearer token auth using
timing-safe comparison. Health, metrics, and docs endpoints remain
open. Auth is skipped in test environment. API_KEY is required in
production via Joi env validation.

Co-authored-by: Cursor <cursoragent@cursor.com>
@lukesmmr
Copy link
Member Author

lukesmmr commented Feb 8, 2026

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 8, 2026

📝 Walkthrough

Walkthrough

This change introduces API key-based Bearer token authentication across the application. A new middleware validates incoming requests against an API_KEY environment variable using constant-time comparison, applied conditionally to REST and GraphQL routes when not in test mode. Supporting configuration, comprehensive test coverage, and OpenAPI documentation updates have been added.

Changes

Cohort / File(s) Summary
Configuration & Documentation
.env.example, openapi.json
Added commented API key configuration guidance with example placeholder; updated OpenAPI security scheme from header-based API key to HTTP Bearer token authentication.
Authentication Middleware
middleware/auth.ts, middleware/auth.test.ts
Implemented new apiKeyAuth middleware using constant-time comparison (timingSafeEqual) to validate Bearer tokens; added comprehensive test suite covering misconfiguration, missing/invalid headers, and successful authentication paths.
Application Integration
app.ts
Wired authentication middleware to REST and GraphQL routes (conditionally when NODE_ENV is not test); added API_KEY environment variable validation required only in production; adjusted ApolloServer initialization after middleware setup.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Middleware as apiKeyAuth<br/>(Middleware)
    participant Config as Environment<br/>(API_KEY)
    participant Handler as Route<br/>Handler

    Client->>Middleware: Request + Authorization:<br/>Bearer [token]
    Middleware->>Config: Read API_KEY
    alt API_KEY missing
        Middleware->>Client: 500 Server Error
    else Authorization header missing
        Middleware->>Client: 401 Unauthorized
    else Token invalid
        Middleware->>Client: 401 Invalid API key
    else Token valid (timing-safe compare)
        Middleware->>Handler: next()
        Handler->>Client: 200 Response
    end
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A bearer token hops through the gate,
Cryptographic checks won't hesitate,
Timing-safe and constant we compare,
No timing attacks shall venture there!
The warren's door now guards with care. 🔐

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding API key authentication middleware for mobile client access, which directly aligns with the changeset introducing apiKeyAuth middleware to protect /api and /graphql routes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/secure-api-with-key

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
middleware/auth.ts (1)

14-17: Consider using a generic error message for the 500 response.

The message "Server misconfigured: API_KEY not set" leaks internal configuration state to the caller. While the Joi validation in app.ts should prevent this in production, a defense-in-depth approach would use a generic message like "Internal server error" and log the details server-side instead.

🛡️ Proposed fix
   if (!apiKey) {
-    res.status(500).json({ error: 'Server misconfigured: API_KEY not set' });
+    console.error('API_KEY environment variable is not set');
+    res.status(500).json({ error: 'Internal server error' });
     return;
   }
openapi.json (1)

414-419: Security scheme correctly updated to reflect Bearer token authentication.

The change from apiKey type to http/bearer aligns with the middleware implementation. The global security reference on line 422 ensures all endpoints require authentication by default in the spec.

Minor nit: the scheme name ApiKeyAuth is slightly misleading now that it's an HTTP Bearer scheme rather than an API-key-in-header scheme. Consider renaming to BearerAuth for clarity, though this is cosmetic.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai
Copy link

coderabbitai bot commented Feb 8, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lukesmmr lukesmmr requested a review from caspear February 8, 2026 11:59
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.

1 participant