|
| 1 | +import request from 'supertest'; |
| 2 | +import { admin, app, closeApplication } from './authTestApp'; |
| 3 | + |
| 4 | +type AuthorizeHook = (params: { adminUser: any }) => Promise<{ allowed?: boolean, error?: string }>; |
| 5 | + |
| 6 | +const authorizeHooks = admin.config.auth.adminUserAuthorize as AuthorizeHook[]; |
| 7 | + |
| 8 | +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; |
| 9 | + |
| 10 | +const login = async (): Promise<string> => { |
| 11 | + const res = await request(app).post('/adminapi/v1/login').send({ username: 'adminforth', password: 'adminforth' }); |
| 12 | + return res.headers['set-cookie'][0].split(';')[0]; |
| 13 | +}; |
| 14 | + |
| 15 | +const tokenPayload = (cookie: string) => |
| 16 | + JSON.parse(Buffer.from(cookie.split('.')[1], 'base64url').toString()); |
| 17 | + |
| 18 | +const checkAuth = (cookie: string) => |
| 19 | + request(app).post('/adminapi/v1/check_auth').set('Cookie', cookie).send({}); |
| 20 | + |
| 21 | +afterAll(async () => { |
| 22 | + await closeApplication(); |
| 23 | +}); |
| 24 | + |
| 25 | +afterEach(() => { |
| 26 | + authorizeHooks.length = 0; |
| 27 | +}); |
| 28 | + |
| 29 | +describe('auth session id', () => { |
| 30 | + it('puts unique session id into auth token on every login', async () => { |
| 31 | + const first = tokenPayload(await login()); |
| 32 | + const second = tokenPayload(await login()); |
| 33 | + |
| 34 | + expect(first.sessionId).toMatch(UUID_RE); |
| 35 | + expect(second.sessionId).toMatch(UUID_RE); |
| 36 | + expect(first.sessionId).not.toEqual(second.sessionId); |
| 37 | + }); |
| 38 | + |
| 39 | + it('exposes same session id to every request done with one login', async () => { |
| 40 | + const seen: string[] = []; |
| 41 | + authorizeHooks.push(async ({ adminUser }) => { seen.push(adminUser.sessionId); return { allowed: true }; }); |
| 42 | + |
| 43 | + const cookie = await login(); |
| 44 | + await checkAuth(cookie); |
| 45 | + await checkAuth(cookie); |
| 46 | + |
| 47 | + expect(seen).toEqual([tokenPayload(cookie).sessionId, tokenPayload(cookie).sessionId]); |
| 48 | + }); |
| 49 | + |
| 50 | + it('keeps sessions of parallel logins apart', async () => { |
| 51 | + const seen: string[] = []; |
| 52 | + authorizeHooks.push(async ({ adminUser }) => { seen.push(adminUser.sessionId); return { allowed: true }; }); |
| 53 | + |
| 54 | + const firstCookie = await login(); |
| 55 | + const secondCookie = await login(); |
| 56 | + await checkAuth(firstCookie); |
| 57 | + await checkAuth(secondCookie); |
| 58 | + |
| 59 | + expect(seen).toEqual([tokenPayload(firstCookie).sessionId, tokenPayload(secondCookie).sessionId]); |
| 60 | + expect(seen[0]).not.toEqual(seen[1]); |
| 61 | + }); |
| 62 | +}); |
0 commit comments