File size: 13,797 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createMockExpressContext } from '../../utils/mocks.js';
import fs from 'fs';
import path from 'path';

/**
 * Note: auth.ts reads AUTOMAKER_API_KEY at module load time.
 * We need to reset modules and reimport for each test to get fresh state.
 */
describe('auth.ts', () => {
  beforeEach(() => {
    vi.resetModules();
    delete process.env.AUTOMAKER_API_KEY;
    delete process.env.AUTOMAKER_HIDE_API_KEY;
    delete process.env.NODE_ENV;
  });

  describe('authMiddleware', () => {
    it('should reject request without any authentication', async () => {
      const { authMiddleware } = await import('@/lib/auth.js');
      const { req, res, next } = createMockExpressContext();

      authMiddleware(req, res, next);

      expect(res.status).toHaveBeenCalledWith(401);
      expect(res.json).toHaveBeenCalledWith({
        success: false,
        error: 'Authentication required.',
      });
      expect(next).not.toHaveBeenCalled();
    });

    it('should reject request with invalid API key', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { authMiddleware } = await import('@/lib/auth.js');
      const { req, res, next } = createMockExpressContext();
      req.headers['x-api-key'] = 'wrong-key';

      authMiddleware(req, res, next);

      expect(res.status).toHaveBeenCalledWith(403);
      expect(res.json).toHaveBeenCalledWith({
        success: false,
        error: 'Invalid API key.',
      });
      expect(next).not.toHaveBeenCalled();
    });

    it('should call next() with valid API key', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { authMiddleware } = await import('@/lib/auth.js');
      const { req, res, next } = createMockExpressContext();
      req.headers['x-api-key'] = 'test-secret-key';

      authMiddleware(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(res.status).not.toHaveBeenCalled();
    });

    it('should authenticate with session token in header', async () => {
      const { authMiddleware, createSession } = await import('@/lib/auth.js');
      const token = await createSession();
      const { req, res, next } = createMockExpressContext();
      req.headers['x-session-token'] = token;

      authMiddleware(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(res.status).not.toHaveBeenCalled();
    });

    it('should reject invalid session token in header', async () => {
      const { authMiddleware } = await import('@/lib/auth.js');
      const { req, res, next } = createMockExpressContext();
      req.headers['x-session-token'] = 'invalid-token';

      authMiddleware(req, res, next);

      expect(res.status).toHaveBeenCalledWith(403);
      expect(res.json).toHaveBeenCalledWith({
        success: false,
        error: 'Invalid or expired session token.',
      });
      expect(next).not.toHaveBeenCalled();
    });

    it('should authenticate with API key in query parameter', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { authMiddleware } = await import('@/lib/auth.js');
      const { req, res, next } = createMockExpressContext();
      req.query.apiKey = 'test-secret-key';

      authMiddleware(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(res.status).not.toHaveBeenCalled();
    });

    it('should authenticate with session cookie', async () => {
      const { authMiddleware, createSession, getSessionCookieName } = await import('@/lib/auth.js');
      const token = await createSession();
      const cookieName = getSessionCookieName();
      const { req, res, next } = createMockExpressContext();
      req.cookies = { [cookieName]: token };

      authMiddleware(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(res.status).not.toHaveBeenCalled();
    });
  });

  describe('createSession', () => {
    it('should create a new session and return token', async () => {
      const { createSession } = await import('@/lib/auth.js');
      const token = await createSession();

      expect(token).toBeDefined();
      expect(typeof token).toBe('string');
      expect(token.length).toBeGreaterThan(0);
    });

    it('should create unique tokens for each session', async () => {
      const { createSession } = await import('@/lib/auth.js');
      const token1 = await createSession();
      const token2 = await createSession();

      expect(token1).not.toBe(token2);
    });
  });

  describe('validateSession', () => {
    it('should validate a valid session token', async () => {
      const { createSession, validateSession } = await import('@/lib/auth.js');
      const token = await createSession();

      expect(validateSession(token)).toBe(true);
    });

    it('should reject invalid session token', async () => {
      const { validateSession } = await import('@/lib/auth.js');

      expect(validateSession('invalid-token')).toBe(false);
    });

    it('should reject expired session token', async () => {
      vi.useFakeTimers();
      const { createSession, validateSession } = await import('@/lib/auth.js');
      const token = await createSession();

      // Advance time past session expiration (30 days)
      vi.advanceTimersByTime(31 * 24 * 60 * 60 * 1000);

      expect(validateSession(token)).toBe(false);
      vi.useRealTimers();
    });
  });

  describe('invalidateSession', () => {
    it('should invalidate a session token', async () => {
      const { createSession, validateSession, invalidateSession } = await import('@/lib/auth.js');
      const token = await createSession();

      expect(validateSession(token)).toBe(true);
      await invalidateSession(token);
      expect(validateSession(token)).toBe(false);
    });
  });

  describe('createWsConnectionToken', () => {
    it('should create a WebSocket connection token', async () => {
      const { createWsConnectionToken } = await import('@/lib/auth.js');
      const token = createWsConnectionToken();

      expect(token).toBeDefined();
      expect(typeof token).toBe('string');
      expect(token.length).toBeGreaterThan(0);
    });

    it('should create unique tokens', async () => {
      const { createWsConnectionToken } = await import('@/lib/auth.js');
      const token1 = createWsConnectionToken();
      const token2 = createWsConnectionToken();

      expect(token1).not.toBe(token2);
    });
  });

  describe('validateWsConnectionToken', () => {
    it('should validate a valid WebSocket token', async () => {
      const { createWsConnectionToken, validateWsConnectionToken } = await import('@/lib/auth.js');
      const token = createWsConnectionToken();

      expect(validateWsConnectionToken(token)).toBe(true);
    });

    it('should reject invalid WebSocket token', async () => {
      const { validateWsConnectionToken } = await import('@/lib/auth.js');

      expect(validateWsConnectionToken('invalid-token')).toBe(false);
    });

    it('should reject expired WebSocket token', async () => {
      vi.useFakeTimers();
      const { createWsConnectionToken, validateWsConnectionToken } = await import('@/lib/auth.js');
      const token = createWsConnectionToken();

      // Advance time past token expiration (5 minutes)
      vi.advanceTimersByTime(6 * 60 * 1000);

      expect(validateWsConnectionToken(token)).toBe(false);
      vi.useRealTimers();
    });

    it('should invalidate token after first use (single-use)', async () => {
      const { createWsConnectionToken, validateWsConnectionToken } = await import('@/lib/auth.js');
      const token = createWsConnectionToken();

      expect(validateWsConnectionToken(token)).toBe(true);
      // Token should be deleted after first use
      expect(validateWsConnectionToken(token)).toBe(false);
    });
  });

  describe('validateApiKey', () => {
    it('should validate correct API key', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { validateApiKey } = await import('@/lib/auth.js');

      expect(validateApiKey('test-secret-key')).toBe(true);
    });

    it('should reject incorrect API key', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { validateApiKey } = await import('@/lib/auth.js');

      expect(validateApiKey('wrong-key')).toBe(false);
    });

    it('should reject empty string', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { validateApiKey } = await import('@/lib/auth.js');

      expect(validateApiKey('')).toBe(false);
    });

    it('should reject null/undefined', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { validateApiKey } = await import('@/lib/auth.js');

      expect(validateApiKey(null as any)).toBe(false);
      expect(validateApiKey(undefined as any)).toBe(false);
    });

    it('should use timing-safe comparison for different lengths', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { validateApiKey } = await import('@/lib/auth.js');

      // Key with different length should be rejected without timing leak
      expect(validateApiKey('short')).toBe(false);
      expect(validateApiKey('very-long-key-that-does-not-match')).toBe(false);
    });
  });

  describe('getSessionCookieOptions', () => {
    it('should return cookie options with httpOnly true', async () => {
      const { getSessionCookieOptions } = await import('@/lib/auth.js');
      const options = getSessionCookieOptions();

      expect(options.httpOnly).toBe(true);
      expect(options.sameSite).toBe('lax');
      expect(options.path).toBe('/');
      expect(options.maxAge).toBeGreaterThan(0);
    });

    it('should set secure to true in production', async () => {
      process.env.NODE_ENV = 'production';

      const { getSessionCookieOptions } = await import('@/lib/auth.js');
      const options = getSessionCookieOptions();

      expect(options.secure).toBe(true);
    });

    it('should set secure to false in non-production', async () => {
      process.env.NODE_ENV = 'development';

      const { getSessionCookieOptions } = await import('@/lib/auth.js');
      const options = getSessionCookieOptions();

      expect(options.secure).toBe(false);
    });
  });

  describe('getSessionCookieName', () => {
    it('should return the session cookie name', async () => {
      const { getSessionCookieName } = await import('@/lib/auth.js');
      const name = getSessionCookieName();

      expect(name).toBe('automaker_session');
    });
  });

  describe('isRequestAuthenticated', () => {
    it('should return true for authenticated request with API key', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { isRequestAuthenticated } = await import('@/lib/auth.js');
      const { req } = createMockExpressContext();
      req.headers['x-api-key'] = 'test-secret-key';

      expect(isRequestAuthenticated(req)).toBe(true);
    });

    it('should return false for unauthenticated request', async () => {
      const { isRequestAuthenticated } = await import('@/lib/auth.js');
      const { req } = createMockExpressContext();

      expect(isRequestAuthenticated(req)).toBe(false);
    });

    it('should return true for authenticated request with session token', async () => {
      const { isRequestAuthenticated, createSession } = await import('@/lib/auth.js');
      const token = await createSession();
      const { req } = createMockExpressContext();
      req.headers['x-session-token'] = token;

      expect(isRequestAuthenticated(req)).toBe(true);
    });
  });

  describe('checkRawAuthentication', () => {
    it('should return true for valid API key in headers', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { checkRawAuthentication } = await import('@/lib/auth.js');

      expect(checkRawAuthentication({ 'x-api-key': 'test-secret-key' }, {}, {})).toBe(true);
    });

    it('should return true for valid session token in headers', async () => {
      const { checkRawAuthentication, createSession } = await import('@/lib/auth.js');
      const token = await createSession();

      expect(checkRawAuthentication({ 'x-session-token': token }, {}, {})).toBe(true);
    });

    it('should return true for valid API key in query', async () => {
      process.env.AUTOMAKER_API_KEY = 'test-secret-key';

      const { checkRawAuthentication } = await import('@/lib/auth.js');

      expect(checkRawAuthentication({}, { apiKey: 'test-secret-key' }, {})).toBe(true);
    });

    it('should return true for valid session cookie', async () => {
      const { checkRawAuthentication, createSession, getSessionCookieName } =
        await import('@/lib/auth.js');
      const token = await createSession();
      const cookieName = getSessionCookieName();

      expect(checkRawAuthentication({}, {}, { [cookieName]: token })).toBe(true);
    });

    it('should return false for invalid credentials', async () => {
      const { checkRawAuthentication } = await import('@/lib/auth.js');

      expect(checkRawAuthentication({}, {}, {})).toBe(false);
    });
  });

  describe('isAuthEnabled', () => {
    it('should always return true (auth is always required)', async () => {
      const { isAuthEnabled } = await import('@/lib/auth.js');
      expect(isAuthEnabled()).toBe(true);
    });
  });

  describe('getAuthStatus', () => {
    it('should return enabled status with api_key_or_session method', async () => {
      const { getAuthStatus } = await import('@/lib/auth.js');
      const status = getAuthStatus();

      expect(status).toEqual({
        enabled: true,
        method: 'api_key_or_session',
      });
    });
  });
});