forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-routes.test.ts
More file actions
588 lines (493 loc) · 19.2 KB
/
Copy pathauth-routes.test.ts
File metadata and controls
588 lines (493 loc) · 19.2 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
// src/app/api/auth/auth-routes.test.ts
import { beforeEach, describe, expect, it, vi } from "vitest"
import { clearSession, createSession, getSession, hashPassword, verifyPassword } from "@/lib/auth"
import { deriveKey, generateSalt } from "@/lib/crypto"
import { db } from "@/lib/db"
import { startScheduler, stopScheduler } from "@/lib/scheduler"
vi.mock("@/lib/db", () => ({
db: {
select: vi.fn(),
insert: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
transaction: vi.fn(),
},
}))
vi.mock("@/lib/db/schema", () => ({
appSettings: {},
}))
vi.mock("@/lib/auth", () => ({
hashPassword: vi.fn(),
verifyPassword: vi.fn(),
createSession: vi.fn(),
createPendingToken: vi.fn(),
getSession: vi.fn(),
clearSession: vi.fn(),
}))
vi.mock("@/lib/crypto", () => ({
generateSalt: vi.fn(),
deriveKey: vi.fn(),
}))
vi.mock("@/lib/scheduler", () => ({
startScheduler: vi.fn(),
stopScheduler: vi.fn(),
}))
vi.mock("@/lib/scheduler-key-store", () => ({
persistSchedulerKey: vi.fn().mockResolvedValue(undefined),
clearSchedulerKey: vi.fn().mockResolvedValue(undefined),
}))
vi.mock("@/lib/lockout", () => ({
checkLockout: vi.fn().mockReturnValue(null),
recordFailedAttempt: vi.fn().mockResolvedValue(undefined),
resetFailedAttempts: vi.fn().mockResolvedValue(undefined),
}))
function makeSelectChain(resolvedValue: unknown) {
const mockLimit = vi.fn().mockResolvedValue(resolvedValue)
const mockFrom = vi.fn().mockReturnValue({ limit: mockLimit })
;(db.select as ReturnType<typeof vi.fn>).mockReturnValue({ from: mockFrom })
return { mockLimit, mockFrom }
}
function _makeInsertChain() {
const mockValues = vi.fn().mockResolvedValue(undefined)
;(db.insert as ReturnType<typeof vi.fn>).mockReturnValue({ values: mockValues })
return { mockValues }
}
/** Mock db.transaction to execute the callback with a mock tx that mirrors db */
function mockTransaction(txSelectResult: unknown) {
const txMockValues = vi.fn().mockResolvedValue(undefined)
const txMockLimit = vi.fn().mockResolvedValue(txSelectResult)
const txMockFrom = vi.fn().mockReturnValue({ limit: txMockLimit })
const tx = {
select: vi.fn().mockReturnValue({ from: txMockFrom }),
insert: vi.fn().mockReturnValue({ values: txMockValues }),
}
;(db.transaction as ReturnType<typeof vi.fn>).mockImplementation(
async (cb: (t: Record<string, unknown>) => Promise<unknown>) => cb(tx)
)
return { tx, txMockValues }
}
describe("POST /api/auth/setup", () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it("returns 200 with success true when not yet configured", async () => {
// Pre-flight check returns empty (not configured)
makeSelectChain([])
// Transaction: tx.select returns empty, tx.insert succeeds
const { txMockValues } = mockTransaction([])
;(hashPassword as ReturnType<typeof vi.fn>).mockResolvedValue("hashed")
;(generateSalt as ReturnType<typeof vi.fn>).mockReturnValue("salt123")
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "admin" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({ success: true })
expect(txMockValues).toHaveBeenCalledWith(
expect.objectContaining({
passwordHash: expect.any(String),
encryptionSalt: expect.any(String),
username: "admin",
})
)
})
it("returns 400 when already configured", async () => {
makeSelectChain([{ id: 1, passwordHash: "hash", encryptionSalt: "salt" }])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "admin" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Already configured" })
})
it("returns 400 for invalid JSON", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "not-json{{{",
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Invalid JSON" })
})
it("returns 400 when password is too short", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "short" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Password must be between 8 and 128 characters" })
})
it("returns 400 when password is too long", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "a".repeat(129) }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Password must be between 8 and 128 characters" })
})
it("returns 400 when password is missing", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Password must be between 8 and 128 characters" })
})
it("accepts password of exactly 8 characters", async () => {
makeSelectChain([])
mockTransaction([])
;(hashPassword as ReturnType<typeof vi.fn>).mockResolvedValue("hashed")
;(generateSalt as ReturnType<typeof vi.fn>).mockReturnValue("salt123")
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "a".repeat(8), username: "testuser" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({ success: true })
})
it("returns 400 when username is missing", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body.error).toContain("Username")
})
it("returns 400 when username is too short", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "ab" }),
})
const response = await POST(req)
expect(response.status).toBe(400)
})
it("returns 400 when username is only whitespace", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: " " }),
})
const response = await POST(req)
expect(response.status).toBe(400)
})
it("returns 400 when username contains control characters", async () => {
makeSelectChain([])
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "user\x00name" }),
})
const response = await POST(req)
expect(response.status).toBe(400)
})
it("accepts username of exactly 3 characters", async () => {
makeSelectChain([])
mockTransaction([])
;(hashPassword as ReturnType<typeof vi.fn>).mockResolvedValue("hashed")
;(generateSalt as ReturnType<typeof vi.fn>).mockReturnValue("salt123")
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "joe" }),
})
const response = await POST(req)
expect(response.status).toBe(200)
})
it("accepts password of exactly 128 characters", async () => {
makeSelectChain([])
mockTransaction([])
;(hashPassword as ReturnType<typeof vi.fn>).mockResolvedValue("hashed")
;(generateSalt as ReturnType<typeof vi.fn>).mockReturnValue("salt123")
const { POST } = await import("./setup/route")
const req = new Request("http://localhost/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "a".repeat(128), username: "testuser" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({ success: true })
})
})
describe("POST /api/auth/login", () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it("returns 200 and calls createSession and startScheduler on success", async () => {
const fakeSettings = {
id: 1,
passwordHash: "hash",
encryptionSalt: "salt",
failedLoginAttempts: 0,
}
makeSelectChain([fakeSettings])
;(verifyPassword as ReturnType<typeof vi.fn>).mockResolvedValue(true)
const fakeKey = Buffer.from("a".repeat(32))
;(deriveKey as ReturnType<typeof vi.fn>).mockResolvedValue(fakeKey)
;(createSession as ReturnType<typeof vi.fn>).mockResolvedValue("token")
;(startScheduler as ReturnType<typeof vi.fn>).mockReturnValue(undefined)
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({ success: true })
expect(createSession).toHaveBeenCalledWith(fakeKey.toString("hex"), undefined)
expect(startScheduler).toHaveBeenCalledWith(fakeKey)
})
it("returns 401 when username is set but not provided", async () => {
const fakeSettings = {
id: 1,
passwordHash: "hash",
encryptionSalt: "salt",
failedLoginAttempts: 0,
username: "admin",
}
makeSelectChain([fakeSettings])
;(verifyPassword as ReturnType<typeof vi.fn>).mockResolvedValue(true)
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123" }),
})
const response = await POST(req)
expect(response.status).toBe(401)
expect(verifyPassword).toHaveBeenCalled()
})
it("returns 401 when username is set but wrong", async () => {
const fakeSettings = {
id: 1,
passwordHash: "hash",
encryptionSalt: "salt",
failedLoginAttempts: 0,
username: "admin",
}
makeSelectChain([fakeSettings])
;(verifyPassword as ReturnType<typeof vi.fn>).mockResolvedValue(true)
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "wrong" }),
})
const response = await POST(req)
expect(response.status).toBe(401)
expect(verifyPassword).toHaveBeenCalled()
})
it("returns 200 when correct username and password provided (case-insensitive)", async () => {
const fakeSettings = {
id: 1,
passwordHash: "hash",
encryptionSalt: "salt",
failedLoginAttempts: 0,
username: "Admin",
}
makeSelectChain([fakeSettings])
;(verifyPassword as ReturnType<typeof vi.fn>).mockResolvedValue(true)
const fakeKey = Buffer.from("a".repeat(32))
;(deriveKey as ReturnType<typeof vi.fn>).mockResolvedValue(fakeKey)
;(createSession as ReturnType<typeof vi.fn>).mockResolvedValue("token")
;(startScheduler as ReturnType<typeof vi.fn>).mockReturnValue(undefined)
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123", username: "admin" }),
})
const response = await POST(req)
expect(response.status).toBe(200)
})
it("returns 400 when not configured", async () => {
makeSelectChain([])
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "valid-password-123" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Not configured. Run setup first." })
})
it("returns 400 for invalid JSON", async () => {
const fakeSettings = { id: 1, passwordHash: "hash", encryptionSalt: "salt" }
makeSelectChain([fakeSettings])
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "not-json{{{",
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Invalid JSON" })
})
it("returns 400 when password is missing", async () => {
const fakeSettings = { id: 1, passwordHash: "hash", encryptionSalt: "salt" }
makeSelectChain([fakeSettings])
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Invalid password" })
})
it("returns 400 when password is too long", async () => {
const fakeSettings = { id: 1, passwordHash: "hash", encryptionSalt: "salt" }
makeSelectChain([fakeSettings])
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "a".repeat(129) }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({ error: "Invalid password" })
})
it("returns 401 for wrong password", async () => {
const fakeSettings = {
id: 1,
passwordHash: "hash",
encryptionSalt: "salt",
failedLoginAttempts: 0,
}
makeSelectChain([fakeSettings])
;(verifyPassword as ReturnType<typeof vi.fn>).mockResolvedValue(false)
const { POST } = await import("./login/route")
const req = new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: "wrong-password-here" }),
})
const response = await POST(req)
const body = await response.json()
expect(response.status).toBe(401)
expect(body).toEqual({ error: "Invalid credentials" })
})
})
describe("POST /api/auth/logout", () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it("clears the session and returns 200 (scheduler keeps running)", async () => {
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue({ encryptionKey: "abc123" })
;(clearSession as ReturnType<typeof vi.fn>).mockResolvedValue(undefined)
const { POST } = await import("./logout/route")
const response = await POST()
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({ success: true })
expect(stopScheduler).not.toHaveBeenCalled()
expect(clearSession).toHaveBeenCalledOnce()
})
it("returns 401 when not authenticated", async () => {
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue(null)
const { POST } = await import("./logout/route")
const response = await POST()
expect(response.status).toBe(401)
})
})
describe("GET /api/auth/status", () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it("returns configured false and authenticated false when neither is set", async () => {
makeSelectChain([])
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue(null)
const { GET } = await import("./status/route")
const response = await GET()
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({
configured: false,
authenticated: false,
totpEnabled: false,
hasUsername: false,
})
})
it("returns configured true and authenticated false when configured but no session", async () => {
makeSelectChain([{ id: 1, passwordHash: "hash", encryptionSalt: "salt" }])
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue(null)
const { GET } = await import("./status/route")
const response = await GET()
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({
configured: true,
authenticated: false,
totpEnabled: false,
hasUsername: false,
})
})
it("returns configured true and authenticated true when both are set", async () => {
makeSelectChain([{ id: 1, passwordHash: "hash", encryptionSalt: "salt" }])
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue({ encryptionKey: "abc123" })
const { GET } = await import("./status/route")
const response = await GET()
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toEqual({
configured: true,
authenticated: true,
totpEnabled: false,
hasUsername: false,
})
})
})