/** * Unit Tests — middleware/api-key-auth.js */ import { describe, it, expect } from 'vitest'; const { extractApiKey } = require('../../middleware/api-key-auth'); describe('api-key-auth', () => { function mockReq(headers = {}, query = {}) { return { headers, query }; } describe('extractApiKey', () => { it('should extract from Authorization Bearer header', () => { const req = mockReq({ authorization: 'Bearer my-secret-key' }); expect(extractApiKey(req)).toBe('my-secret-key'); }); it('should extract from X-API-Key header', () => { const req = mockReq({ 'x-api-key': 'another-key' }); expect(extractApiKey(req)).toBe('another-key'); }); it('should extract from query param', () => { const req = mockReq({}, { api_key: 'query-key' }); expect(extractApiKey(req)).toBe('query-key'); }); it('should prefer Bearer over X-API-Key', () => { const req = mockReq({ authorization: 'Bearer bearer-key', 'x-api-key': 'x-key', }); expect(extractApiKey(req)).toBe('bearer-key'); }); it('should return null when no key provided', () => { const req = mockReq(); expect(extractApiKey(req)).toBeNull(); }); it('should trim whitespace', () => { const req = mockReq({ authorization: 'Bearer spaced-key ' }); expect(extractApiKey(req)).toBe('spaced-key'); }); it('should ignore non-Bearer auth headers', () => { const req = mockReq({ authorization: 'Basic abc123' }); expect(extractApiKey(req)).toBeNull(); }); }); });