serverless-docker
Version:
This is a proof of concept to see if we can replicate Amazon API Gateway using docker images to run lambda
138 lines (113 loc) • 3.36 kB
JavaScript
const BbPromise = require('bluebird')
const authorizer = {
authorize: jest.fn(),
}
jest.mock('./index', () => authorizer)
const middleware = require('./middleware')
describe('middleware', () => {
const logger = {}
let req = null
let res = null
let next = null
beforeEach(() => {
req = {
logger,
get: jest.fn(),
}
res = {}
next = jest.fn()
authorizer.authorize.mockClear()
})
it('should invoke custom authorizer', () => {
const token = 'token'
const context = {
http: {
integration: 'lambda-proxy',
path: '/test/path',
method: 'post',
cors: null,
authorizer: {
name: 'authorizer',
identitySource: 'method.request.header.Authorization',
},
},
}
req.get.mockImplementation(() => token)
authorizer.authorize.mockImplementation(() => BbPromise.resolve())
req.context = context
middleware()(req, res, next).then(() => {
expect(req.get.mock.calls.length).toBe(1)
expect(req.get.mock.calls[0][0]).toBe('Authorization')
expect(authorizer.authorize.mock.calls.length).toBe(1)
expect(authorizer.authorize.mock.calls[0][0]).toBe(context)
expect(authorizer.authorize.mock.calls[0][1]).toBe(token)
expect(authorizer.authorize.mock.calls[0][1]).toBe(logger)
expect(next.mock.calls.length).toBe(1)
})
})
it('should skip if no custom authorizer', () => {
const token = 'token'
const context = {
http: {
integration: 'lambda-proxy',
path: '/test/path',
method: 'post',
cors: null,
authorizer: null,
},
}
req.get.mockImplementation(() => token)
authorizer.authorize.mockImplementation(() => BbPromise.resolve())
req.context = context
middleware()(req, res, next).then(() => {
expect(req.get.mock.calls.length).toBe(0)
expect(authorizer.authorize.mock.calls.length).toBe(0)
expect(next.mock.calls.length).toBe(1)
})
})
it('should skip custom authorizer if cors and OPTIONS request', () => {
const token = 'token'
const context = {
http: {
integration: 'lambda-proxy',
path: '/test/path',
method: 'post',
cors: true,
authorizer: {
name: 'authorizer',
identitySource: 'method.request.header.Authorization',
},
},
}
req.get.mockImplementation(() => token)
authorizer.authorize.mockImplementation(() => BbPromise.resolve())
req.method = 'OPTIONS'
req.context = context
middleware()(req, res, next).then(() => {
expect(req.get.mock.calls.length).toBe(0)
expect(authorizer.authorize.mock.calls.length).toBe(0)
expect(next.mock.calls.length).toBe(1)
})
})
it('should throw if identity source is not header', () => {
const token = 'token'
const context = {
http: {
integration: 'lambda-proxy',
path: '/test/path',
method: 'post',
authorizer: {
name: 'authorizer',
identitySource: 'blah',
},
},
}
req.get.mockImplementation(() => token)
authorizer.authorize.mockImplementation(() => BbPromise.resolve())
req.context = context
expect(() => {
middleware()(req, res, next)
}).toThrow()
})
})