forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiKeys.test.ts
More file actions
600 lines (508 loc) · 19.7 KB
/
Copy pathapiKeys.test.ts
File metadata and controls
600 lines (508 loc) · 19.7 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import {
generateApiKey,
hashApiKey,
verifyApiKey,
createApiKey,
validateApiKey,
rotateApiKey,
deactivateApiKey,
computeKeySelector
} from '../apiKeys';
import { database } from '../../database';
describe('API Key Utilities', () => {
beforeEach(async () => {
await database.clearDatabase();
});
describe('generateApiKey', () => {
it('should generate a 64-character hex string', () => {
const apiKey = generateApiKey();
expect(apiKey).toMatch(/^[a-f0-9]{64}$/);
expect(apiKey).toHaveLength(64);
});
it('should generate unique keys', () => {
const key1 = generateApiKey();
const key2 = generateApiKey();
expect(key1).not.toBe(key2);
});
});
describe('hashApiKey', () => {
it('should hash an API key with salt', () => {
const apiKey = 'test-api-key';
const result = hashApiKey(apiKey);
expect(result).toHaveProperty('salt');
expect(result).toHaveProperty('hash');
expect(result.salt).toMatch(/^[a-f0-9]{32}$/);
expect(result.hash).toMatch(/^[a-f0-9]{128}$/);
});
it('should generate different hashes for the same key', () => {
const apiKey = 'test-api-key';
const result1 = hashApiKey(apiKey);
const result2 = hashApiKey(apiKey);
expect(result1.salt).not.toBe(result2.salt);
expect(result1.hash).not.toBe(result2.hash);
});
});
describe('verifyApiKey', () => {
it('should verify a correct API key', () => {
const apiKey = 'test-api-key';
const { salt, hash } = hashApiKey(apiKey);
const isValid = verifyApiKey(apiKey, salt, hash);
expect(isValid).toBe(true);
});
it('should reject an incorrect API key', () => {
const apiKey = 'test-api-key';
const wrongKey = 'wrong-api-key';
const { salt, hash } = hashApiKey(apiKey);
const isValid = verifyApiKey(wrongKey, salt, hash);
expect(isValid).toBe(false);
});
it('should reject with wrong salt', () => {
const apiKey = 'test-api-key';
const { hash } = hashApiKey(apiKey);
const wrongSalt = hashApiKey('different').salt;
const isValid = verifyApiKey(apiKey, wrongSalt, hash);
expect(isValid).toBe(false);
});
});
describe('computeKeySelector', () => {
it('should produce a deterministic selector for the same key', () => {
const apiKey = 'test-api-key';
const selector1 = computeKeySelector(apiKey);
const selector2 = computeKeySelector(apiKey);
expect(selector1).toBe(selector2);
});
it('should produce different selectors for different keys', () => {
const selector1 = computeKeySelector('key-one');
const selector2 = computeKeySelector('key-two');
expect(selector1).not.toBe(selector2);
});
it('should produce a 64-character hex string', () => {
const selector = computeKeySelector('test-api-key');
expect(selector).toMatch(/^[a-f0-9]{64}$/);
});
it('should not be reversible (SHA-256 preimage resistance)', () => {
const key = generateApiKey();
const selector = computeKeySelector(key);
// A SHA-256 hash is 256 bits = 32 bytes = 64 hex chars
// It is computationally infeasible to recover the original key
expect(selector).toHaveLength(64);
});
});
describe('createApiKey', () => {
it('should create a new API key with key_selector', async () => {
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123'
};
const result = await createApiKey(request);
expect(result).toHaveProperty('apiKey');
expect(result).toHaveProperty('info');
expect(result.apiKey).toMatch(/^[a-f0-9]{64}$/);
expect(result.info.name).toBe('Test Key');
expect(result.info.scope).toEqual(['contracts:read']);
expect(result.info.createdBy).toBe('user123');
expect(result.info.isActive).toBe(true);
// Verify key_selector was stored
const db = await (database as any).loadDatabase();
const storedKey = db.api_keys.find((k: any) => k.name === 'Test Key');
expect(storedKey.key_selector).toBeDefined();
expect(storedKey.key_selector).toMatch(/^[a-f0-9]{64}$/);
expect(storedKey.key_selector).toBe(computeKeySelector(result.apiKey));
});
it('should store API key with expiration', async () => {
const expiresAt = new Date('2024-12-31T23:59:59Z');
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123',
expiresAt
};
const result = await createApiKey(request);
expect(result.info.expiresAt).toEqual(expiresAt);
});
});
describe('validateApiKey - indexed O(1) lookup', () => {
it('should validate a correct API key via selector index', async () => {
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123'
};
const { apiKey } = await createApiKey(request);
const result = await validateApiKey(apiKey);
expect(result).not.toBeNull();
expect(result!.name).toBe('Test Key');
expect(result!.scope).toEqual(['contracts:read']);
expect(result!.createdBy).toBe('user123');
});
it('should reject an invalid API key', async () => {
const result = await validateApiKey('invalid-key');
expect(result).toBeNull();
});
it('should reject an expired API key', async () => {
const pastDate = new Date('2020-01-01T00:00:00Z');
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123',
expiresAt: pastDate
};
const { apiKey } = await createApiKey(request);
const result = await validateApiKey(apiKey);
expect(result).toBeNull();
});
it('should deactivate an expired key on validation attempt', async () => {
const pastDate = new Date('2020-01-01T00:00:00Z');
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123',
expiresAt: pastDate
};
const { apiKey } = await createApiKey(request);
await validateApiKey(apiKey);
const db = await (database as any).loadDatabase();
const storedKey = db.api_keys.find((k: any) => k.name === 'Test Key');
expect(storedKey.is_active).toBe(false);
});
it('should update last used timestamp', async () => {
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123'
};
const { apiKey } = await createApiKey(request);
await validateApiKey(apiKey);
const db = await (database as any).loadDatabase();
const storedKey = db.api_keys.find((key: any) => key.name === 'Test Key');
expect(storedKey.last_used_at).toBeDefined();
expect(storedKey.last_used_at).toBeInstanceOf(Date);
});
it('should find the correct key among many keys (O(1) property)', async () => {
// Create multiple keys to verify we find the right one without scanning all
const keys: string[] = [];
for (let i = 0; i < 10; i++) {
const { apiKey } = await createApiKey({
name: `Key ${i}`,
scope: ['test:read'],
createdBy: 'user123'
});
keys.push(apiKey);
}
// Validate each key individually
for (let i = 0; i < keys.length; i++) {
const result = await validateApiKey(keys[i]);
expect(result).not.toBeNull();
expect(result!.name).toBe(`Key ${i}`);
}
});
it('should reject a revoked (deactivated) key', async () => {
const request = {
name: 'Revocable Key',
scope: ['test:read'],
createdBy: 'user123'
};
const { apiKey, info } = await createApiKey(request);
// First validation should succeed
const firstResult = await validateApiKey(apiKey);
expect(firstResult).not.toBeNull();
// Deactivate the key
await deactivateApiKey(info.id);
// Second validation should fail
const secondResult = await validateApiKey(apiKey);
expect(secondResult).toBeNull();
});
it('should return null when no keys exist', async () => {
const result = await validateApiKey(generateApiKey());
expect(result).toBeNull();
});
it('should backfill key_selector for legacy keys', async () => {
// Simulate a legacy key without key_selector by inserting directly via loadDatabase
const apiKeyPlain = generateApiKey();
const { salt, hash } = hashApiKey(apiKeyPlain);
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: require('crypto').randomUUID(),
name: 'Legacy Key',
key_hash: `${salt}:${hash}`,
scope: ['legacy:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
// No key_selector field
});
await (database as any).saveDatabase();
// Validate should still work via legacy fallback
const result = await validateApiKey(apiKeyPlain);
expect(result).not.toBeNull();
expect(result!.name).toBe('Legacy Key');
// After validation, key_selector should be backfilled
const db2 = await (database as any).loadDatabase();
const storedKey = db2.api_keys.find((k: any) => k.name === 'Legacy Key');
expect(storedKey.key_selector).toBe(computeKeySelector(apiKeyPlain));
});
it('should find the correct key among multiple legacy keys', async () => {
// Simulate THREE legacy keys without key_selector (only the last one matches the API key)
const matchingKeyPlain = generateApiKey();
const { salt: matchSalt, hash: matchHash } = hashApiKey(matchingKeyPlain);
const db = await (database as any).loadDatabase();
// Push two non-matching legacy keys first
for (let i = 0; i < 2; i++) {
const otherKey = generateApiKey();
const { salt, hash } = hashApiKey(otherKey);
db.api_keys.push({
id: require('crypto').randomUUID(),
name: `Other Legacy Key ${i}`,
key_hash: `${salt}:${hash}`,
scope: ['legacy:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
// No key_selector field
});
}
// Push the matching legacy key last
db.api_keys.push({
id: require('crypto').randomUUID(),
name: 'Target Legacy Key',
key_hash: `${matchSalt}:${matchHash}`,
scope: ['legacy:write'],
created_by: 'user456',
created_at: new Date(),
updated_at: new Date(),
is_active: true
// No key_selector field
});
await (database as any).saveDatabase();
// Validate should find the correct key even though it's not the first legacy key
const result = await validateApiKey(matchingKeyPlain);
expect(result).not.toBeNull();
expect(result!.name).toBe('Target Legacy Key');
expect(result!.scope).toEqual(['legacy:write']);
expect(result!.createdBy).toBe('user456');
// After validation, the matched key should be backfilled
const db2 = await (database as any).loadDatabase();
const matchedKey = db2.api_keys.find((k: any) => k.name === 'Target Legacy Key');
expect(matchedKey.key_selector).toBe(computeKeySelector(matchingKeyPlain));
// Other legacy keys should remain without key_selector
const otherKeys = db2.api_keys.filter((k: any) => k.name !== 'Target Legacy Key');
for (const k of otherKeys) {
expect(k.key_selector).toBeUndefined();
}
});
});
describe('rotateApiKey', () => {
it('should rotate an existing API key and update selector', async () => {
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123'
};
const { apiKey: originalKey, info: originalInfo } = await createApiKey(request);
// Original key should work
expect(await validateApiKey(originalKey)).not.toBeNull();
const result = await rotateApiKey(originalInfo.id);
expect(result).not.toBeNull();
expect(result).toHaveProperty('apiKey');
expect(result).toHaveProperty('info');
expect(result!.apiKey).toMatch(/^[a-f0-9]{64}$/);
expect(result!.info.id).toBe(originalInfo.id);
expect(result!.info.name).toBe(originalInfo.name);
expect(result!.info.scope).toEqual(originalInfo.scope);
// New key should work
expect(await validateApiKey(result!.apiKey)).not.toBeNull();
// Old key should no longer work
expect(await validateApiKey(originalKey)).toBeNull();
// Verify selector was updated
const db = await (database as any).loadDatabase();
const storedKey = db.api_keys.find((k: any) => k.id === originalInfo.id);
expect(storedKey.key_selector).toBe(computeKeySelector(result!.apiKey));
});
it('should return null for non-existent key', async () => {
const result = await rotateApiKey('non-existent-id');
expect(result).toBeNull();
});
});
describe('deactivateApiKey', () => {
it('should deactivate an existing API key', async () => {
const request = {
name: 'Test Key',
scope: ['contracts:read'],
createdBy: 'user123'
};
const { apiKey, info } = await createApiKey(request);
const result = await deactivateApiKey(info.id);
expect(result).toBe(true);
// Key should no longer be valid (even with correct key)
const validationResult = await validateApiKey(apiKey);
expect(validationResult).toBeNull();
});
it('should return false for non-existent key', async () => {
const result = await deactivateApiKey('non-existent-id');
expect(result).toBe(false);
});
});
describe('validateApiKey - malformed stored credential handling', () => {
const crypto = require('crypto');
it('should reject keys with empty stored credential', async () => {
// Insert a key with empty key_hash directly
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Empty Hash Key',
key_hash: '',
key_selector: computeKeySelector('some-key'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key');
expect(result).toBeNull();
});
it('should reject keys with missing colon separator', async () => {
// Insert a key with no colon in key_hash
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'No Colon Key',
key_hash: 'abcdef0123456789abcdef0123456789', // valid hex but no colon
key_selector: computeKeySelector('some-key-2'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-2');
expect(result).toBeNull();
});
it('should reject keys with extra colons', async () => {
// Insert a key with multiple colons
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Extra Colon Key',
key_hash: 'salt:hash:extra',
key_selector: computeKeySelector('some-key-3'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-3');
expect(result).toBeNull();
});
it('should reject keys with wrong-length hex (salt too short)', async () => {
// Salt should be 32 hex chars, here it's too short
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Short Salt Key',
key_hash: 'abc:hash1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
key_selector: computeKeySelector('some-key-4'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-4');
expect(result).toBeNull();
});
it('should reject keys with wrong-length hex (hash too short)', async () => {
// Hash should be 128 hex chars, here it's too short
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Short Hash Key',
key_hash: 'abcdef0123456789abcdef0123456789:abc',
key_selector: computeKeySelector('some-key-5'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-5');
expect(result).toBeNull();
});
it('should reject keys with empty salt part', async () => {
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Empty Salt Key',
key_hash: ':hash1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
key_selector: computeKeySelector('some-key-6'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-6');
expect(result).toBeNull();
});
it('should reject keys with empty hash part', async () => {
const db = await (database as any).loadDatabase();
db.api_keys.push({
id: crypto.randomUUID(),
name: 'Empty Hash Part Key',
key_hash: 'abcdef0123456789abcdef0123456789:',
key_selector: computeKeySelector('some-key-7'),
scope: ['test:read'],
created_by: 'user123',
created_at: new Date(),
updated_at: new Date(),
is_active: true
});
await (database as any).saveDatabase();
const result = await validateApiKey('some-key-7');
expect(result).toBeNull();
});
it('should still verify valid keys correctly', async () => {
// This is a regression test to ensure the fix doesn't break valid key verification
const request = {
name: 'Valid Key Test',
scope: ['contracts:read'],
createdBy: 'user123'
};
const { apiKey } = await createApiKey(request);
const result = await validateApiKey(apiKey);
expect(result).not.toBeNull();
expect(result!.name).toBe('Valid Key Test');
expect(result!.isActive).toBe(true);
});
it('should not throw exceptions on malformed input - fail closed', async () => {
// This test ensures no exceptions are thrown for any malformed input
const malformedInputs = [
'',
'no-colon',
'multiple:colons:here',
'short:hash123',
'salt0123456789abcdef0123456789abcdef:short',
':hash...',
'salt:',
' : ',
'invalidhex!@#:invalidhex!@#'
];
for (const key of malformedInputs) {
// Should not throw - should return null cleanly
await expect(async () => {
await validateApiKey(key);
}).not.toThrow();
}
});
});
});