import { execute, getUser, startSession } from 'test/rest'; import { getCustomRepository } from 'typeorm'; import { ApiClientRepository } from '@/repositories'; import { HttpStatusCodes } from './types'; describe('rest api authentication', () => { it('fails if user is not authorized', async () => { const user = await getUser(); const username = user.username; // credentials not provided const response1 = await execute({ method: 'post', url: '/v3/api-keys', data: { username }, }); expect(response1.status).toBe(HttpStatusCodes.UNAUTHORIZED); expect(response1.body).toEqual({ message: 'Invalid credentials' }); // wrong username const wrongUsernameKey = Buffer.from('wrong1username.password').toString( 'base64url' ); const wrongUsernameAuthHeader = Buffer.from( `create_${wrongUsernameKey}:` ).toString('base64'); const response3 = await execute({ method: 'post', url: '/v3/api-keys', headers: { Authorization: `Basic ${wrongUsernameAuthHeader}`, }, data: { username }, }); expect(response3.status).toBe(401); expect(response3.body).toEqual({ message: 'Unauthorized' }); // wrong password const apiKey = await getCustomRepository( ApiClientRepository ).generateApiKey({ user, }); const wrongPasswordKey = Buffer.from(`${apiKey}dabc`).toString('base64url'); const wrongPasswordAuthHeader = Buffer.from( `create_${wrongPasswordKey}:` ).toString('base64'); const response4 = await execute({ method: 'post', url: '/v3/api-keys', headers: { Authorization: `Basic ${wrongPasswordAuthHeader}`, }, data: { username }, }); expect(response4.status).toBe(HttpStatusCodes.UNAUTHORIZED); expect(response4.body).toEqual({ message: 'Unauthorized' }); }); it('blocks non admins from accessing admin only routes', async () => { const username = (await getUser()).username; const { execute } = await startSession(); const response = await execute({ method: 'post', url: '/v3/api-keys', data: { username }, }); expect(response.status).toBe(HttpStatusCodes.FORBIDDEN); expect(response.body).toEqual({ message: 'Forbidden' }); }); it('allows admins to access admin only routes', async () => { const username = (await getUser()).username; const { execute } = await startSession({ makeAdmin: true, }); const response = await execute({ method: 'post', url: '/v3/api-keys', data: { username }, }); expect(response.status).toBe(HttpStatusCodes.CREATED); }); it('allows master admins to access admin only routes', async () => { const username = (await getUser()).username; const masterAdminAuthHeader = Buffer.from( `${process.env.ROOT_API_KEY_CLIENT_ID}:${process.env.ROOT_API_KEY_CLIENT_SECRET}` ).toString('base64'); const response = await execute({ method: 'post', url: '/v3/api-keys', data: { username }, headers: { Authorization: `Basic ${masterAdminAuthHeader}`, }, }); expect(response.status).toBe(HttpStatusCodes.CREATED); }); });