-
Notifications
You must be signed in to change notification settings - Fork 0
Add API key authentication middleware for mobile client access #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lukesmmr
wants to merge
1
commit into
feat/api-expansion-mobile-app
Choose a base branch
from
feat/secure-api-with-key
base: feat/api-expansion-mobile-app
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| process.env.NODE_ENV = 'test'; | ||
|
|
||
| import { describe, it, expect, beforeEach, afterEach, jest } from '@jest/globals'; | ||
| import { apiKeyAuth } from './auth.js'; | ||
| import type { Request, Response, NextFunction } from 'express'; | ||
|
|
||
| const VALID_API_KEY = 'a'.repeat(64); | ||
|
|
||
| describe('apiKeyAuth middleware', () => { | ||
| let req: Partial<Request>; | ||
| let res: Partial<Response> & { status: jest.Mock; json: jest.Mock }; | ||
| let next: jest.Mock; | ||
| let originalApiKey: string | undefined; | ||
|
|
||
| beforeEach(() => { | ||
| originalApiKey = process.env.API_KEY; | ||
| process.env.API_KEY = VALID_API_KEY; | ||
|
|
||
| req = { | ||
| headers: {}, | ||
| } as Partial<Request>; | ||
|
|
||
| res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn(), | ||
| } as Partial<Response> & { status: jest.Mock; json: jest.Mock }; | ||
|
|
||
| next = jest.fn(); | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| if (originalApiKey === undefined) { | ||
| delete process.env.API_KEY; | ||
| } else { | ||
| process.env.API_KEY = originalApiKey; | ||
| } | ||
| }); | ||
|
|
||
| it('should return 500 when API_KEY env var is not set', () => { | ||
| delete process.env.API_KEY; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(500); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Server misconfigured: API_KEY not set' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return 401 when Authorization header is missing', () => { | ||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Missing or invalid Authorization header' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return 401 when Authorization header does not start with Bearer', () => { | ||
| req.headers = { authorization: 'Basic some-token' }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Missing or invalid Authorization header' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return 401 when Bearer token is empty', () => { | ||
| req.headers = { authorization: 'Bearer ' }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid API key' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return 401 when API key is invalid', () => { | ||
| req.headers = { authorization: 'Bearer wrong-key' }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid API key' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return 401 when API key has correct length but wrong content', () => { | ||
| const wrongKey = 'b'.repeat(64); | ||
| req.headers = { authorization: `Bearer ${wrongKey}` }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid API key' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should call next() when API key is valid', () => { | ||
| req.headers = { authorization: `Bearer ${VALID_API_KEY}` }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(res.status).not.toHaveBeenCalled(); | ||
| expect(res.json).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should use timing-safe comparison (same-length keys take similar time)', () => { | ||
| // This test verifies the code path exercises timingSafeEqual | ||
| // by checking that a key of equal length to the valid key is still rejected | ||
| const sameLengthWrongKey = 'z'.repeat(64); | ||
| req.headers = { authorization: `Bearer ${sameLengthWrongKey}` }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid API key' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should reject key that is a substring of the valid key', () => { | ||
| const partialKey = VALID_API_KEY.slice(0, 32); | ||
| req.headers = { authorization: `Bearer ${partialKey}` }; | ||
|
|
||
| apiKeyAuth(req as Request, res as Response, next as NextFunction); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid API key' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { Request, Response, NextFunction } from 'express'; | ||
| import { timingSafeEqual } from 'crypto'; | ||
|
|
||
| /** | ||
| * Express middleware that authenticates requests using a Bearer token | ||
| * in the Authorization header. The token is compared against the API_KEY | ||
| * environment variable using constant-time comparison to prevent timing attacks. | ||
| * | ||
| * Excluded from auth (handled at the app level): /healthz, /readyz, /metrics, /api-docs | ||
| */ | ||
| export function apiKeyAuth(req: Request, res: Response, next: NextFunction): void { | ||
| const apiKey = process.env.API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| res.status(500).json({ error: 'Server misconfigured: API_KEY not set' }); | ||
| return; | ||
| } | ||
|
|
||
| const authHeader = req.headers.authorization; | ||
|
|
||
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | ||
| res.status(401).json({ error: 'Missing or invalid Authorization header' }); | ||
| return; | ||
| } | ||
|
|
||
| const token = authHeader.slice(7); // Strip 'Bearer ' prefix | ||
| const tokenBuffer = Buffer.from(token); | ||
| const keyBuffer = Buffer.from(apiKey); | ||
|
|
||
| if (tokenBuffer.length !== keyBuffer.length || !timingSafeEqual(tokenBuffer, keyBuffer)) { | ||
| res.status(401).json({ error: 'Invalid API key' }); | ||
| return; | ||
| } | ||
|
|
||
| next(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
user input should only load tokens cut down to their maximum length.
(authHeader.length!==apiKey.length+7)should already res 401, not allocating a buffer for it