|
| 1 | +import type { APIGatewayProxyEvent } from 'aws-lambda' |
| 2 | +import { test, expect, describe } from 'vitest' |
| 3 | + |
| 4 | +import { parseAuthorizationHeader } from '../index' |
| 5 | + |
| 6 | +describe('parseAuthorizationHeader', () => { |
| 7 | + test('throws error if Authorization header is not valid', () => { |
| 8 | + const invalidHeaders = [ |
| 9 | + undefined, |
| 10 | + null, |
| 11 | + '', |
| 12 | + 'Bearer', |
| 13 | + 'Bearer ', |
| 14 | + 'Bearer token with spaces', |
| 15 | + 'Token', |
| 16 | + 'Token ', |
| 17 | + 'Token token with spaces', |
| 18 | + ] |
| 19 | + |
| 20 | + invalidHeaders.forEach((header) => { |
| 21 | + expect(() => |
| 22 | + // @ts-expect-error That's what we're testing |
| 23 | + parseAuthorizationHeader({ headers: { Authorization: header } }), |
| 24 | + ).toThrowError('The `Authorization` header is not valid.') |
| 25 | + }) |
| 26 | + }) |
| 27 | + |
| 28 | + test('returns the schema and token from valid Authorization header', () => { |
| 29 | + const validHeaders = [ |
| 30 | + 'Bearer token', |
| 31 | + 'Bearer 12345', |
| 32 | + 'Token token', |
| 33 | + 'Token 12345', |
| 34 | + ] |
| 35 | + |
| 36 | + validHeaders.forEach((header) => { |
| 37 | + // We only care about the headers in the event |
| 38 | + const result = parseAuthorizationHeader({ |
| 39 | + headers: { Authorization: header }, |
| 40 | + } as unknown as APIGatewayProxyEvent) |
| 41 | + |
| 42 | + expect(result).toEqual({ |
| 43 | + schema: header.split(' ')[0], |
| 44 | + token: header.split(' ')[1], |
| 45 | + }) |
| 46 | + }) |
| 47 | + }) |
| 48 | + |
| 49 | + test('Handles different lower-casing of the authorization header', () => { |
| 50 | + const result = parseAuthorizationHeader({ |
| 51 | + headers: { authorization: 'Bearer bazinga' }, |
| 52 | + } as unknown as APIGatewayProxyEvent) |
| 53 | + |
| 54 | + expect(result).toEqual({ |
| 55 | + schema: 'Bearer', |
| 56 | + token: 'bazinga', |
| 57 | + }) |
| 58 | + }) |
| 59 | + |
| 60 | + test('Handles different capital-casing of the Authorization header', () => { |
| 61 | + const result = parseAuthorizationHeader({ |
| 62 | + headers: { Authorization: 'Bearer bazinga' }, |
| 63 | + } as unknown as APIGatewayProxyEvent) |
| 64 | + |
| 65 | + expect(result).toEqual({ |
| 66 | + schema: 'Bearer', |
| 67 | + token: 'bazinga', |
| 68 | + }) |
| 69 | + }) |
| 70 | +}) |
0 commit comments