Skip to content

Commit f68acec

Browse files
committed
Fix dbAuth middleware and update tests
1 parent 71fd715 commit f68acec

File tree

2 files changed

+205
-154
lines changed

2 files changed

+205
-154
lines changed

packages/auth-providers/dbAuth/middleware/src/__tests__/initDbAuthMiddleware.test.ts

Lines changed: 126 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from 'node:path'
22

33
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
44

5+
import { dbAuthSession } from '@redwoodjs/auth-dbauth-api'
56
import {
67
MiddlewareRequest as MWRequest,
78
MiddlewareRequest,
@@ -18,13 +19,36 @@ const FIXTURE_PATH = path.resolve(
1819

1920
beforeAll(() => {
2021
process.env.RWJS_CWD = FIXTURE_PATH
22+
23+
// Mock the session decryption
24+
vi.mock('@redwoodjs/auth-dbauth-api', async (importOriginal) => {
25+
const original = (await importOriginal()) as any
26+
return {
27+
...original,
28+
dbAuthSession: vi.fn().mockImplementation((req, cookieName) => {
29+
if (
30+
req.headers
31+
.get('Cookie')
32+
.includes(`${cookieName}=this_is_the_only_correct_session`)
33+
) {
34+
return {
35+
currentUser: {
36+
37+
id: 'mocked-current-user-1',
38+
},
39+
mockedSession: 'this_is_the_only_correct_session',
40+
}
41+
}
42+
}),
43+
}
44+
})
2145
})
2246

2347
afterAll(() => {
2448
delete process.env.RWJS_CWD
2549
})
2650

27-
describe('initDbAuthMiddleware()', () => {
51+
describe('dbAuthMiddleware', () => {
2852
it('When no cookie headers, pass through the response', async () => {
2953
const options: DbAuthMiddlewareOptions = {
3054
cookieName: '8911',
@@ -53,15 +77,14 @@ describe('initDbAuthMiddleware()', () => {
5377
})
5478

5579
it('When it has a cookie header, decrypts and sets server auth context', async () => {
56-
const cookieHeader =
57-
'session=ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w=='
80+
const cookieHeader = 'session=this_is_the_only_correct_session'
5881

5982
const options: DbAuthMiddlewareOptions = {
60-
cookieName: '8911',
6183
getCurrentUser: vi.fn(async () => {
6284
return { id: 'mocked-current-user-1', email: '[email protected]' }
6385
}),
6486
dbAuthHandler: vi.fn(),
87+
extractRoles: vi.fn(() => ['f1driver']),
6588
}
6689
const [middleware] = initDbAuthMiddleware(options)
6790

@@ -77,8 +100,59 @@ describe('initDbAuthMiddleware()', () => {
77100
const res = await middleware(mwReq, MiddlewareResponse.next())
78101

79102
expect(mwReq.serverAuthState.get()).toEqual({
80-
cookieHeader:
81-
'session=ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w==',
103+
cookieHeader: 'session=this_is_the_only_correct_session',
104+
currentUser: {
105+
106+
id: 'mocked-current-user-1',
107+
},
108+
hasError: false,
109+
isAuthenticated: true,
110+
loading: false,
111+
userMetadata: {
112+
113+
id: 'mocked-current-user-1',
114+
},
115+
roles: ['f1driver'],
116+
})
117+
118+
expect(options.extractRoles).toHaveBeenCalledWith({
119+
currentUser: {
120+
121+
id: 'mocked-current-user-1',
122+
},
123+
mockedSession: 'this_is_the_only_correct_session',
124+
})
125+
126+
// Allow react render, because body is not defined, and status code not redirect
127+
expect(res).toHaveProperty('body', undefined)
128+
expect(res).toHaveProperty('status', 200)
129+
})
130+
131+
it('Will use the cookie name option correctly', async () => {
132+
const cookieHeader = 'bazinga_8911=this_is_the_only_correct_session'
133+
134+
const options: DbAuthMiddlewareOptions = {
135+
getCurrentUser: vi.fn(async () => {
136+
return { id: 'mocked-current-user-1', email: '[email protected]' }
137+
}),
138+
dbAuthHandler: vi.fn(),
139+
cookieName: 'bazinga_%port%',
140+
}
141+
const [middleware] = initDbAuthMiddleware(options)
142+
143+
const mwReq = new MiddlewareRequest(
144+
new Request('http://bazinga.new/kittens', {
145+
method: 'GET',
146+
headers: {
147+
Cookie: cookieHeader,
148+
},
149+
}),
150+
)
151+
152+
const res = await middleware(mwReq, MiddlewareResponse.next())
153+
154+
expect(mwReq.serverAuthState.get()).toEqual({
155+
cookieHeader: 'bazinga_8911=this_is_the_only_correct_session',
82156
currentUser: {
83157
84158
id: 'mocked-current-user-1',
@@ -90,6 +164,7 @@ describe('initDbAuthMiddleware()', () => {
90164
91165
id: 'mocked-current-user-1',
92166
},
167+
// No extract roles function, so it should be empty
93168
roles: [],
94169
})
95170

@@ -98,6 +173,39 @@ describe('initDbAuthMiddleware()', () => {
98173
expect(res).toHaveProperty('status', 200)
99174
})
100175

176+
it('handles a currentUser request', async () => {
177+
const cookieHeader = 'session=this_is_the_only_correct_session'
178+
const request = new Request(
179+
'http://localhost:8910/middleware/dbauth/currentUser',
180+
{
181+
method: 'GET',
182+
headers: {
183+
Cookie: cookieHeader,
184+
},
185+
},
186+
)
187+
188+
const req = new MWRequest(request)
189+
const cookie = req.headers.get('Cookie')
190+
191+
expect(cookie).toBe(cookieHeader)
192+
193+
const currentUser = { user: { id: 100, email: '[email protected]' } }
194+
195+
const options: DbAuthMiddlewareOptions = {
196+
getCurrentUser: async () => {
197+
return currentUser
198+
},
199+
dbAuthHandler: vi.fn(),
200+
}
201+
const [middleware] = initDbAuthMiddleware(options)
202+
203+
const res = await middleware(req, MiddlewareResponse.next())
204+
205+
expect(res).toBeDefined()
206+
expect(res?.body).toBe(JSON.stringify({ currentUser }))
207+
})
208+
101209
describe('handle all supported dbAuth verbs (aka methods) and their HTTP methods', async () => {
102210
/**
103211
* Supported verbs and their corresponding HTTP methods:
@@ -300,13 +408,12 @@ describe('initDbAuthMiddleware()', () => {
300408
const req = new MWRequest(request)
301409

302410
const options: DbAuthMiddlewareOptions = {
303-
cookieName: 'session_8911',
304411
getCurrentUser: async () => {
305412
return { user: { id: 100, email: '[email protected]' } }
306413
},
307414
dbAuthHandler: async () => {
308415
return {
309-
body: '',
416+
body: 'getTokenResponse',
310417
headers: {},
311418
statusCode: 200,
312419
}
@@ -316,14 +423,9 @@ describe('initDbAuthMiddleware()', () => {
316423

317424
const res = await middleware(req, MiddlewareResponse.next())
318425
expect(res).toBeDefined()
319-
320-
const serverAuthState = req.serverAuthState.get()
321-
expect(serverAuthState.isAuthenticated).toBe(true)
322-
expect(serverAuthState.currentUser).toEqual({
323-
user: { id: 100, email: '[email protected]' },
324-
})
325-
expect(serverAuthState.cookieHeader).toBe(cookieHeader)
426+
expect(res?.body).toBe('getTokenResponse')
326427
})
428+
327429
it('handles a validateResetToken request', async () => {
328430
const request = new Request(
329431
'http://localhost:8911/middleware/dbauth/auth?method=validateResetToken',
@@ -361,8 +463,9 @@ describe('initDbAuthMiddleware()', () => {
361463
const serverAuthState = req.serverAuthState.get()
362464
expect(serverAuthState.isAuthenticated).toBe(false)
363465
})
466+
364467
it('handles a webAuthnRegOptions request', async () => {
365-
const body = JSON.stringify({
468+
const regOptionsBody = JSON.stringify({
366469
r: { id: 1 },
367470
user: { user: { id: 100, email: '[email protected]' } },
368471
challenge: 'challenge',
@@ -387,7 +490,7 @@ describe('initDbAuthMiddleware()', () => {
387490
},
388491
dbAuthHandler: async () => {
389492
return {
390-
body,
493+
body: regOptionsBody,
391494
headers: {},
392495
statusCode: 200,
393496
}
@@ -396,10 +499,7 @@ describe('initDbAuthMiddleware()', () => {
396499
const [middleware] = initDbAuthMiddleware(options)
397500

398501
const res = await middleware(req, MiddlewareResponse.next())
399-
expect(res).toBeDefined()
400-
// should the body be the webAuth reg options?
401-
// but get requests need a cookie to be set?
402-
// expect(res?.body).toBeDefined()
502+
expect(res?.body).toBe(regOptionsBody)
403503
})
404504
// @todo: implement the following tests when try out webAuth
405505
// it('handles a webAuthnRegister', async () => {
@@ -412,49 +512,6 @@ describe('initDbAuthMiddleware()', () => {
412512
// //: 'POST',
413513
// })
414514
})
415-
it('handles a currentUser request', async () => {
416-
// encrypted session taken fom dbAuth tests
417-
// I cannot figure out why the header here has to be session
418-
// but the cookieName session_8911 to work properly
419-
const cookieHeader =
420-
'session=ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w=='
421-
const request = new Request(
422-
'http://localhost:8911/middleware/dbauth/currentUser',
423-
{
424-
method: 'GET',
425-
headers: {
426-
Cookie: cookieHeader,
427-
},
428-
},
429-
)
430-
431-
const req = new MWRequest(request)
432-
const cookie = req.headers.get('Cookie')
433-
434-
expect(cookie).toBe(cookieHeader)
435-
436-
const currentUser = { user: { id: 100, email: '[email protected]' } }
437-
438-
const options: DbAuthMiddlewareOptions = {
439-
cookieName: 'session_8911',
440-
getCurrentUser: async () => {
441-
return currentUser
442-
},
443-
dbAuthHandler: async () => {
444-
return {
445-
body: '',
446-
headers: {},
447-
statusCode: 200,
448-
}
449-
},
450-
}
451-
const [middleware] = initDbAuthMiddleware(options)
452-
453-
const res = await middleware(req, MiddlewareResponse.next())
454-
455-
expect(res).toBeDefined()
456-
expect(res?.body).toBe(JSON.stringify({ currentUser }))
457-
})
458515

459516
describe('handle exception cases', async () => {
460517
const unauthenticatedServerAuthState = {
@@ -463,6 +520,11 @@ describe('initDbAuthMiddleware()', () => {
463520
roles: [],
464521
}
465522

523+
beforeAll(() => {
524+
// So that we don't see errors in console when running negative cases
525+
vi.spyOn(console, 'error').mockImplementation(() => {})
526+
})
527+
466528
it('handles a POST that is not one of the supported dbAuth verbs and still build headers when passing along the request', async () => {
467529
const request = new Request(
468530
'http://localhost:8911/middleware/dbauth/unsupportedVerb',
@@ -502,48 +564,6 @@ describe('initDbAuthMiddleware()', () => {
502564
const serverAuthState = req.serverAuthState.get()
503565
expect(serverAuthState).toHaveProperty('isAuthenticated', false)
504566
})
505-
it('handles a GET request with correct cookies', async () => {
506-
// encrypted session taken fom dbAuth tests
507-
// I cannot figure out why the header here has to be session
508-
// but the cookieName session_8911 to work properly
509-
const cookieHeader =
510-
'session=ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w=='
511-
const request = new Request('http://localhost:8911/functions/hello', {
512-
method: 'GET',
513-
headers: {
514-
Cookie: cookieHeader,
515-
},
516-
})
517-
518-
const req = new MWRequest(request)
519-
const cookie = req.headers.get('Cookie')
520-
521-
expect(cookie).toBe(cookieHeader)
522-
523-
const options: DbAuthMiddlewareOptions = {
524-
cookieName: 'session_8911',
525-
getCurrentUser: async () => {
526-
return { user: { id: 100, email: '[email protected]' } }
527-
},
528-
dbAuthHandler: async () => {
529-
return {
530-
body: '',
531-
headers: {},
532-
statusCode: 200,
533-
}
534-
},
535-
}
536-
const [middleware] = initDbAuthMiddleware(options)
537-
538-
const res = await middleware(req, MiddlewareResponse.next())
539-
const serverAuthState = req.serverAuthState.get()
540-
541-
expect(res).toBeDefined()
542-
expect(serverAuthState.isAuthenticated).toBe(true)
543-
expect(serverAuthState.currentUser).toEqual({
544-
user: { id: 100, email: '[email protected]' },
545-
})
546-
})
547567

548568
it('handles a GET request with incorrect cookies (bad decrypt)', async () => {
549569
const request = new Request(

0 commit comments

Comments
 (0)