api-key-auth.test.js
1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 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();
});
});
});