forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.test.js
More file actions
264 lines (221 loc) · 8.61 KB
/
Copy pathauth.test.js
File metadata and controls
264 lines (221 loc) · 8.61 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
'use strict';
process.env.ADMIN_API_KEY = 'a'.repeat(64);
const crypto = require('crypto');
const mockStore = new Map();
const mockSets = new Map();
const mockSortedSets = new Map();
const mockRedis = {
smembers: jest.fn(async (key) => [...(mockSets.get(key) || [])]),
sadd: jest.fn(async (key, val) => {
if (!mockSets.has(key)) mockSets.set(key, new Set());
mockSets.get(key).add(val);
}),
srem: jest.fn(async (key, val) => {
mockSets.get(key)?.delete(val);
}),
zadd: jest.fn(async (key, score, member) => {
if (!mockSortedSets.has(key)) mockSortedSets.set(key, new Map());
mockSortedSets.get(key).set(member, score);
}),
zrem: jest.fn(async (key, member) => {
mockSortedSets.get(key)?.delete(member);
}),
zrevrange: jest.fn(async (key, start, stop) => {
const sortedSet = mockSortedSets.get(key);
if (!sortedSet) return [];
const entries = Array.from(sortedSet.entries()).sort((a, b) => b[1] - a[1]);
const startIdx = start === -1 ? entries.length + start : start;
const stopIdx = stop === -1 ? entries.length + stop : stop;
return entries.slice(startIdx, stopIdx + 1).map(([member]) => member);
}),
};
jest.mock('../src/services/cache', () => ({
getClient: () => mockRedis,
get: jest.fn(async (key) => {
const v = mockStore.get(key);
return v !== undefined ? JSON.parse(JSON.stringify(v)) : null;
}),
set: jest.fn(async (key, value) => {
mockStore.set(key, JSON.parse(JSON.stringify(value)));
}),
del: jest.fn(async (key) => {
mockStore.delete(key);
}),
}));
jest.mock('../src/logger', () => ({
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
}));
const express = require('express');
const request = require('supertest');
const { requireApiKey } = require('../src/middleware/auth');
const keysRouter = require('../src/routes/keys');
const apiKeys = require('../src/services/apiKeys');
const cache = require('../src/services/cache');
const { errorHandler } = require('../src/middleware/errorHandler');
function buildProtectedApp(options) {
const app = express();
app.use(express.json());
app.get('/protected', requireApiKey(options), (req, res) => {
res.json({ ok: true, key: req.apiKey });
});
app.use(errorHandler);
return app;
}
function buildKeysApp() {
const app = express();
app.use(express.json());
app.use('/api/v1', keysRouter);
app.use(errorHandler);
return app;
}
beforeEach(() => {
mockStore.clear();
mockSets.clear();
mockSortedSets.clear();
cache.get.mockClear();
cache.set.mockClear();
cache.del.mockClear();
mockRedis.smembers.mockClear();
mockRedis.sadd.mockClear();
mockRedis.srem.mockClear();
mockRedis.zadd.mockClear();
mockRedis.zrem.mockClear();
mockRedis.zrevrange.mockClear();
});
describe('requireApiKey middleware', () => {
test('missing API key returns consistent 401 body', async () => {
const app = buildProtectedApp();
const res = await request(app).get('/protected');
expect(res.status).toBe(401);
expect(res.body.error).toMatchObject({ code: 'UNAUTHORIZED', message: 'Missing or invalid API key' });
});
test('invalid API key returns consistent 401 body', async () => {
const app = buildProtectedApp();
const res = await request(app)
.get('/protected')
.set('Authorization', 'Bearer bad-key');
expect(res.status).toBe(401);
expect(res.body.error).toMatchObject({ code: 'UNAUTHORIZED', message: 'Missing or invalid API key' });
});
test('ADMIN_API_KEY authenticates bootstrap admin requests', async () => {
const app = buildProtectedApp({ scopes: ['admin'] });
const res = await request(app)
.get('/protected')
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`);
expect(res.status).toBe(200);
expect(res.body.key.id).toBe('admin');
expect(res.body.key.scopes).toContain('admin');
});
test('ADMIN_API_KEY comparison uses timingSafeEqual on fixed-length digests', async () => {
const timingSpy = jest.spyOn(crypto, 'timingSafeEqual');
try {
const result = await apiKeys.validateApiKey(process.env.ADMIN_API_KEY);
expect(result.id).toBe('admin');
expect(timingSpy).toHaveBeenCalledTimes(1);
const [actualDigest, expectedDigest] = timingSpy.mock.calls[0];
expect(Buffer.isBuffer(actualDigest)).toBe(true);
expect(Buffer.isBuffer(expectedDigest)).toBe(true);
expect(actualDigest).toHaveLength(32);
expect(expectedDigest).toHaveLength(32);
} finally {
timingSpy.mockRestore();
}
});
test('wrong-length admin API key guesses do not throw before constant-time comparison', async () => {
const timingSpy = jest.spyOn(crypto, 'timingSafeEqual');
try {
await expect(apiKeys.validateApiKey('short')).resolves.toBeNull();
expect(timingSpy).toHaveBeenCalledTimes(1);
const [actualDigest, expectedDigest] = timingSpy.mock.calls[0];
expect(actualDigest).toHaveLength(32);
expect(expectedDigest).toHaveLength(32);
} finally {
timingSpy.mockRestore();
}
});
test('generated API key authenticates and updates last_used_at', async () => {
const created = await apiKeys.createKey({ label: 'alerts worker', scopes: ['alerts'] });
const app = buildProtectedApp();
const res = await request(app)
.get('/protected')
.set('Authorization', `Bearer ${created.api_key}`);
expect(res.status).toBe(200);
const stored = await apiKeys.getKey(created.key.id);
expect(stored.last_used_at).toEqual(expect.any(String));
});
test('rejects API key with 403 when required scope is missing', async () => {
const created = await apiKeys.createKey({ label: 'alerts worker', scopes: ['alerts'] });
const app = buildProtectedApp({ scopes: ['webhooks'] });
const res = await request(app)
.get('/protected')
.set('Authorization', `Bearer ${created.api_key}`);
expect(res.status).toBe(403);
expect(res.body.error).toMatchObject({
code: 'FORBIDDEN',
message: 'Insufficient API key scope',
});
});
test('allows API key when required scope matches', async () => {
const created = await apiKeys.createKey({ label: 'webhooks worker', scopes: ['webhooks'] });
const app = buildProtectedApp({ scopes: ['webhooks'] });
const res = await request(app)
.get('/protected')
.set('Authorization', `Bearer ${created.api_key}`);
expect(res.status).toBe(200);
expect(res.body.ok).toBe(true);
});
});
describe('API key management routes', () => {
test('admin can create, list, and revoke API keys without persisting raw key', async () => {
const app = buildKeysApp();
const createRes = await request(app)
.post('/api/v1/keys')
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`)
.send({ label: 'alerts worker', scopes: ['alerts'] });
expect(createRes.status).toBe(201);
expect(createRes.body.api_key).toMatch(/^[a-f0-9]{64}$/);
expect(createRes.body.key).toMatchObject({
label: 'alerts worker',
scopes: ['alerts'],
last_used_at: null,
});
expect(createRes.body.key.key_hash).toBeUndefined();
const stored = [...mockStore.values()].map((value) => JSON.stringify(value)).join('\n');
expect(stored).not.toContain(createRes.body.api_key);
expect(stored).toContain(apiKeys.hashApiKey(createRes.body.api_key));
const listRes = await request(app)
.get('/api/v1/keys')
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`);
expect(listRes.status).toBe(200);
expect(listRes.body.keys).toHaveLength(1);
expect(listRes.body.keys[0].key_hash).toBeUndefined();
const deleteRes = await request(app)
.delete(`/api/v1/keys/${createRes.body.key.id}`)
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`);
expect(deleteRes.status).toBe(200);
expect(deleteRes.body.deleted).toBe(true);
expect(await apiKeys.getKey(createRes.body.key.id)).toBeNull();
});
test('key management routes require admin API key', async () => {
const app = buildKeysApp();
const res = await request(app).get('/api/v1/keys');
expect(res.status).toBe(401);
expect(res.body.error).toMatchObject({ code: 'UNAUTHORIZED', message: 'Missing or invalid API key' });
});
test('create key rejects blank labels', async () => {
const app = buildKeysApp();
const res = await request(app)
.post('/api/v1/keys')
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`)
.send({ label: ' ' });
expect(res.status).toBe(400);
expect(res.body.error).toMatchObject({
code: 'VALIDATION_ERROR',
message: 'Validation failed',
});
expect(res.body.error.details.fields.label).toBeDefined();
});
});