1 | const test = require('ava')
|
2 | const helpers = require('./_helpers')
|
3 | const fixtures = require('./fixtures')
|
4 | const apiKey = require('../src/apiKey')
|
5 |
|
6 | const cfg = helpers.getOptions({ publicKey: fixtures.common.publicKeyJwk })
|
7 | const mockResponse = {
|
8 | access_token: 'barfoo'
|
9 | }
|
10 | const defaults = {
|
11 | url: 'http://barfoo.com/foo/bar',
|
12 | in: 'headers',
|
13 | prefix: 'Api-Key ',
|
14 | name: 'authorization',
|
15 | request: {},
|
16 | tokenPath: 'access_token'
|
17 | }
|
18 |
|
19 | test('Do not replace api key with bearer token because of missing options', async (t) => {
|
20 | const server = await helpers.getServer(cfg)
|
21 |
|
22 | apiKey.init(server, cfg)
|
23 |
|
24 | const { result } = await server.inject({
|
25 | url: '/proxy',
|
26 | headers: {
|
27 | authorization: 'Api-Key foobar'
|
28 | }
|
29 | })
|
30 |
|
31 | t.is(result.headers.authorization, 'Api-Key foobar')
|
32 | t.is(Object.keys(result.query).length, 0)
|
33 | })
|
34 |
|
35 | test('Do not replace api key with bearer token because of missing api key', async (t) => {
|
36 | const server = await helpers.getServer(cfg)
|
37 |
|
38 | apiKey.init(server, Object.assign({
|
39 | apiKey: defaults
|
40 | }, cfg))
|
41 |
|
42 | const { result } = await server.inject({
|
43 | url: '/proxy'
|
44 | })
|
45 |
|
46 | t.falsy(result.headers.authorization)
|
47 | t.is(Object.keys(result.query).length, 0)
|
48 | })
|
49 |
|
50 | test('Do not replace api key with bearer token because of failing request', async (t) => {
|
51 | helpers.mockApiKey(401, mockResponse, false)
|
52 | const server = await helpers.getServer(cfg)
|
53 |
|
54 | apiKey.init(server, Object.assign({
|
55 | apiKey: defaults
|
56 | }, cfg))
|
57 |
|
58 | const res = await server.inject({
|
59 | url: '/proxy',
|
60 | headers: {
|
61 | authorization: 'Api-Key foobar'
|
62 | }
|
63 | })
|
64 |
|
65 | t.is(res.statusCode, 401)
|
66 | t.truthy(res.result.attributes.reason)
|
67 | })
|
68 |
|
69 | test('Replace api key with bearer token', async (t) => {
|
70 | helpers.mockApiKey(200, mockResponse, false)
|
71 | const server = await helpers.getServer(cfg)
|
72 |
|
73 | apiKey.init(server, Object.assign({
|
74 | apiKey: defaults
|
75 | }, cfg))
|
76 |
|
77 | const { result } = await server.inject({
|
78 | url: '/proxy',
|
79 | headers: {
|
80 | authorization: 'Api-Key foobar'
|
81 | }
|
82 | })
|
83 |
|
84 | t.is(result.headers.authorization, 'Bearer barfoo')
|
85 | t.is(Object.keys(result.query).length, 0)
|
86 | })
|