@defra/lis-hubs-infra-core 0.12.0 → 0.13.0-lreg-563.alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/base-client.js +59 -33
- package/src/base-client.test.js +131 -22
- package/src/index.js +1 -1
- package/src/proxy-plugin.js +30 -8
- package/src/proxy-plugin.test.js +97 -7
- package/src/service-token/constants.js +1 -0
- package/src/service-token/issuer.js +83 -0
- package/src/service-token/issuer.test.js +282 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@defra/lis-hubs-infra-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0-lreg-563.alpha.2",
|
|
4
4
|
"description": "Shared hub mechanics for livestock platform.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"repository": {
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"author": "Defra DDTS",
|
|
32
32
|
"license": "OGL-UK-3.0",
|
|
33
33
|
"dependencies": {
|
|
34
|
+
"@aws-sdk/client-sts": "3.1143.0",
|
|
34
35
|
"@defra/lis-hubs-infra-registry": "^0.4.0",
|
|
35
36
|
"@elastic/ecs-pino-format": "1.5.0",
|
|
36
37
|
"@hapi/h2o2": "10.0.4",
|
package/src/base-client.js
CHANGED
|
@@ -2,9 +2,18 @@ import Wreck from '@hapi/wreck'
|
|
|
2
2
|
|
|
3
3
|
import * as requestContext from './request-context.js'
|
|
4
4
|
import { getServiceBaseUrl } from './get-service-base-url.js'
|
|
5
|
+
import { getServiceToken } from './service-token/issuer.js'
|
|
5
6
|
|
|
6
7
|
const BAD_REQUEST = 400
|
|
7
8
|
const UNPROCESSABLE_ENTITY = 422
|
|
9
|
+
const SERVICE_UNAVAILABLE = 503
|
|
10
|
+
|
|
11
|
+
const ABSOLUTE_URL_PATTERN = /^([a-z][a-z0-9+.-]*:|\/\/)/i
|
|
12
|
+
|
|
13
|
+
export class ServiceTokenError extends Error {
|
|
14
|
+
name = 'ServiceTokenError'
|
|
15
|
+
statusCode = SERVICE_UNAVAILABLE
|
|
16
|
+
}
|
|
8
17
|
|
|
9
18
|
/**
|
|
10
19
|
* A generic Wreck wrapper for a BE4FE or other upstream service, shared
|
|
@@ -18,28 +27,17 @@ export class BaseClient {
|
|
|
18
27
|
_baseUrl
|
|
19
28
|
|
|
20
29
|
/** @protected */
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
/** @protected */
|
|
24
|
-
_apiKeyHeader
|
|
30
|
+
_serviceName
|
|
25
31
|
|
|
26
32
|
/** @protected */
|
|
27
33
|
_timeout
|
|
28
34
|
|
|
29
35
|
/**
|
|
30
|
-
* @param {{ environment: string, serviceName: string, port?: number,
|
|
36
|
+
* @param {{ environment: string, serviceName: string, port?: number, timeout?: number }} options
|
|
31
37
|
*/
|
|
32
|
-
constructor({
|
|
33
|
-
environment,
|
|
34
|
-
serviceName,
|
|
35
|
-
port,
|
|
36
|
-
apiKey,
|
|
37
|
-
apiKeyHeader,
|
|
38
|
-
timeout
|
|
39
|
-
}) {
|
|
38
|
+
constructor({ environment, serviceName, port, timeout }) {
|
|
40
39
|
this._baseUrl = getServiceBaseUrl(environment, serviceName, port).origin
|
|
41
|
-
this.
|
|
42
|
-
this._apiKeyHeader = apiKeyHeader
|
|
40
|
+
this._serviceName = serviceName
|
|
43
41
|
this._timeout = timeout
|
|
44
42
|
}
|
|
45
43
|
|
|
@@ -50,7 +48,7 @@ export class BaseClient {
|
|
|
50
48
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
51
49
|
*/
|
|
52
50
|
_get(path, options) {
|
|
53
|
-
return this._request('GET', path,
|
|
51
|
+
return this._request('GET', path, options)
|
|
54
52
|
}
|
|
55
53
|
|
|
56
54
|
/**
|
|
@@ -60,7 +58,7 @@ export class BaseClient {
|
|
|
60
58
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
61
59
|
*/
|
|
62
60
|
_post(path, options) {
|
|
63
|
-
return this._request('POST', path,
|
|
61
|
+
return this._request('POST', path, options)
|
|
64
62
|
}
|
|
65
63
|
|
|
66
64
|
/**
|
|
@@ -70,7 +68,7 @@ export class BaseClient {
|
|
|
70
68
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
71
69
|
*/
|
|
72
70
|
_put(path, options) {
|
|
73
|
-
return this._request('PUT', path,
|
|
71
|
+
return this._request('PUT', path, options)
|
|
74
72
|
}
|
|
75
73
|
|
|
76
74
|
/**
|
|
@@ -80,7 +78,7 @@ export class BaseClient {
|
|
|
80
78
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
81
79
|
*/
|
|
82
80
|
_patch(path, options) {
|
|
83
|
-
return this._request('PATCH', path,
|
|
81
|
+
return this._request('PATCH', path, options)
|
|
84
82
|
}
|
|
85
83
|
|
|
86
84
|
/**
|
|
@@ -90,52 +88,80 @@ export class BaseClient {
|
|
|
90
88
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
91
89
|
*/
|
|
92
90
|
_delete(path, options) {
|
|
93
|
-
return this._request('DELETE', path,
|
|
91
|
+
return this._request('DELETE', path, options)
|
|
94
92
|
}
|
|
95
93
|
|
|
96
94
|
/**
|
|
97
95
|
* @protected
|
|
98
96
|
* @param {object} [options] caller-supplied Wreck request options
|
|
99
|
-
* @returns {object} Wreck request options with baseUrl/json/timeout/headers applied
|
|
97
|
+
* @returns {Promise<object>} Wreck request options with baseUrl/json/timeout/headers applied
|
|
100
98
|
*/
|
|
101
|
-
_buildOptions(options = {}) {
|
|
99
|
+
async _buildOptions(options = {}) {
|
|
102
100
|
return {
|
|
103
|
-
baseUrl: this._baseUrl,
|
|
104
101
|
json: true,
|
|
105
|
-
timeout: this._timeout,
|
|
106
102
|
...options,
|
|
107
|
-
|
|
103
|
+
baseUrl: this._baseUrl,
|
|
104
|
+
timeout: this._timeout,
|
|
105
|
+
headers: await this._buildHeaders(options.headers)
|
|
108
106
|
}
|
|
109
107
|
}
|
|
110
108
|
|
|
111
109
|
/**
|
|
112
110
|
* @protected
|
|
113
111
|
* @param {object} [callerHeaders] headers supplied on this call
|
|
114
|
-
* @returns {object} correlation,
|
|
112
|
+
* @returns {Promise<object>} correlation, caller and service token headers merged
|
|
115
113
|
*/
|
|
116
|
-
_buildHeaders(callerHeaders) {
|
|
114
|
+
async _buildHeaders(callerHeaders) {
|
|
117
115
|
const headers = { ...requestContext.getHeaders() }
|
|
118
116
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
117
|
+
const authorization = await this.#getAuthorization()
|
|
118
|
+
const otherCallerHeaders = Object.fromEntries(
|
|
119
|
+
Object.entries(callerHeaders ?? {}).filter(
|
|
120
|
+
([name]) => name.toLowerCase() !== 'authorization'
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return { ...headers, ...otherCallerHeaders, authorization }
|
|
125
|
+
}
|
|
122
126
|
|
|
123
|
-
|
|
127
|
+
async #getAuthorization() {
|
|
128
|
+
try {
|
|
129
|
+
const token = await getServiceToken(this._serviceName)
|
|
130
|
+
return `Bearer ${token}`
|
|
131
|
+
} catch (cause) {
|
|
132
|
+
throw new ServiceTokenError(
|
|
133
|
+
`Failed to get a service token for ${this._serviceName}`,
|
|
134
|
+
{ cause }
|
|
135
|
+
)
|
|
136
|
+
}
|
|
124
137
|
}
|
|
125
138
|
|
|
126
139
|
/**
|
|
127
140
|
* @protected
|
|
128
141
|
* @param {string} method HTTP method
|
|
129
142
|
* @param {string} path Path relative to baseUrl
|
|
130
|
-
* @param {object}
|
|
143
|
+
* @param {object} [callerOptions] caller-supplied Wreck request options
|
|
131
144
|
* @returns {Promise<object>} the Wreck result ({ res, payload })
|
|
132
145
|
*/
|
|
133
|
-
async _request(method, path,
|
|
146
|
+
async _request(method, path, callerOptions) {
|
|
147
|
+
// An absolute URL would send the service token to a host other than this
|
|
148
|
+
// client's own service.
|
|
149
|
+
if (ABSOLUTE_URL_PATTERN.test(path)) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
'BaseClient paths must be relative to the service base URL'
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let options
|
|
134
156
|
let res
|
|
135
157
|
|
|
136
158
|
try {
|
|
159
|
+
options = await this._buildOptions(callerOptions)
|
|
137
160
|
res = await Wreck.request(method, path, options)
|
|
138
161
|
} catch (error) {
|
|
162
|
+
if (error instanceof ServiceTokenError) {
|
|
163
|
+
throw error
|
|
164
|
+
}
|
|
139
165
|
throw this.#parseError(error.output?.statusCode, error.data?.payload)
|
|
140
166
|
}
|
|
141
167
|
|
package/src/base-client.test.js
CHANGED
|
@@ -4,14 +4,17 @@ import Wreck from '@hapi/wreck'
|
|
|
4
4
|
|
|
5
5
|
import * as requestContext from './request-context.js'
|
|
6
6
|
import { getServiceBaseUrl } from './get-service-base-url.js'
|
|
7
|
-
import {
|
|
7
|
+
import { getServiceToken } from './service-token/issuer.js'
|
|
8
|
+
import { BaseClient, ServiceTokenError } from './base-client.js'
|
|
8
9
|
|
|
9
10
|
vi.mock('./request-context.js')
|
|
10
11
|
vi.mock('./get-service-base-url.js')
|
|
12
|
+
vi.mock('./service-token/issuer.js')
|
|
11
13
|
|
|
12
14
|
const mocks = {
|
|
13
15
|
requestContextGetHeaders: vi.mocked(requestContext.getHeaders),
|
|
14
|
-
getServiceBaseUrl: vi.mocked(getServiceBaseUrl)
|
|
16
|
+
getServiceBaseUrl: vi.mocked(getServiceBaseUrl),
|
|
17
|
+
getServiceToken: vi.mocked(getServiceToken)
|
|
15
18
|
}
|
|
16
19
|
|
|
17
20
|
function createClient(options = {}) {
|
|
@@ -29,6 +32,7 @@ beforeEach(() => {
|
|
|
29
32
|
'x-cdp-request-id': 'correlation-1'
|
|
30
33
|
})
|
|
31
34
|
mocks.getServiceBaseUrl.mockReturnValue(new URL('http://localhost:8085'))
|
|
35
|
+
mocks.getServiceToken.mockResolvedValue('service-token')
|
|
32
36
|
})
|
|
33
37
|
|
|
34
38
|
afterEach(() => {
|
|
@@ -63,14 +67,10 @@ describe('request verbs', () => {
|
|
|
63
67
|
['_patch', 'PATCH'],
|
|
64
68
|
['_delete', 'DELETE']
|
|
65
69
|
])(
|
|
66
|
-
'it sends %s requests via Wreck.request with the
|
|
70
|
+
'it sends %s requests via Wreck.request with the correlation and service token headers',
|
|
67
71
|
async (method, httpMethod) => {
|
|
68
72
|
// Arrange
|
|
69
|
-
const client = createClient({
|
|
70
|
-
apiKey: 'test-api-key',
|
|
71
|
-
apiKeyHeader: 'x-api-key',
|
|
72
|
-
timeout: 5000
|
|
73
|
-
})
|
|
73
|
+
const client = createClient({ timeout: 5000 })
|
|
74
74
|
const res = { statusCode: 200 }
|
|
75
75
|
const request = vi.spyOn(Wreck, 'request').mockResolvedValue(res)
|
|
76
76
|
const read = vi.spyOn(Wreck, 'read').mockResolvedValue({ data: [] })
|
|
@@ -89,48 +89,157 @@ describe('request verbs', () => {
|
|
|
89
89
|
expect(options.headers).toEqual({
|
|
90
90
|
'x-correlation-id': 'correlation-1',
|
|
91
91
|
'x-cdp-request-id': 'correlation-1',
|
|
92
|
-
|
|
92
|
+
authorization: 'Bearer service-token'
|
|
93
93
|
})
|
|
94
94
|
expect(read).toHaveBeenCalledWith(res, options)
|
|
95
95
|
expect(result).toEqual({ res, payload: { data: [] } })
|
|
96
96
|
}
|
|
97
97
|
)
|
|
98
98
|
|
|
99
|
-
test('it
|
|
99
|
+
test('it lets per-call headers override the defaults', async () => {
|
|
100
|
+
// Arrange
|
|
101
|
+
const client = createClient()
|
|
102
|
+
vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
|
|
103
|
+
vi.spyOn(Wreck, 'read').mockResolvedValue({})
|
|
104
|
+
|
|
105
|
+
// Act
|
|
106
|
+
await client._get('api/cattle/UK123', {
|
|
107
|
+
headers: { 'x-correlation-id': 'override-id' }
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
// Assert
|
|
111
|
+
expect(Wreck.request.mock.calls[0][2].headers['x-correlation-id']).toBe(
|
|
112
|
+
'override-id'
|
|
113
|
+
)
|
|
114
|
+
})
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
describe('service token', () => {
|
|
118
|
+
test('it requests the token for the target service as the audience', async () => {
|
|
100
119
|
// Arrange
|
|
101
120
|
const client = createClient()
|
|
102
121
|
vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
|
|
103
|
-
vi.spyOn(Wreck, 'read').mockResolvedValue({
|
|
122
|
+
vi.spyOn(Wreck, 'read').mockResolvedValue({})
|
|
104
123
|
|
|
105
124
|
// Act
|
|
106
125
|
await client._get('api/users/user-1/cphs')
|
|
107
126
|
|
|
108
127
|
// Assert
|
|
109
|
-
expect(
|
|
110
|
-
|
|
111
|
-
'
|
|
112
|
-
|
|
128
|
+
expect(mocks.getServiceToken).toHaveBeenCalledWith('lis-be4fe-cattle-home')
|
|
129
|
+
expect(Wreck.request.mock.calls[0][2].headers.authorization).toBe(
|
|
130
|
+
'Bearer service-token'
|
|
131
|
+
)
|
|
113
132
|
})
|
|
114
133
|
|
|
115
|
-
test('it
|
|
134
|
+
test('it applies correlation, caller then service token headers in that order', async () => {
|
|
116
135
|
// Arrange
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
136
|
+
mocks.requestContextGetHeaders.mockReturnValue({
|
|
137
|
+
authorization: 'Bearer correlation',
|
|
138
|
+
'x-correlation-id': 'correlation'
|
|
120
139
|
})
|
|
140
|
+
const client = createClient()
|
|
121
141
|
vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
|
|
122
142
|
vi.spyOn(Wreck, 'read').mockResolvedValue({})
|
|
123
143
|
|
|
124
144
|
// Act
|
|
145
|
+
await client._get('api/cattle/UK123')
|
|
125
146
|
await client._get('api/cattle/UK123', {
|
|
126
|
-
headers: { 'x-
|
|
147
|
+
headers: { authorization: 'Bearer caller', 'x-correlation-id': 'caller' }
|
|
127
148
|
})
|
|
128
149
|
|
|
129
150
|
// Assert
|
|
130
|
-
|
|
131
|
-
|
|
151
|
+
const [first, second] = Wreck.request.mock.calls.map(
|
|
152
|
+
([, , options]) => options.headers
|
|
132
153
|
)
|
|
154
|
+
expect(first).toEqual({
|
|
155
|
+
authorization: 'Bearer service-token',
|
|
156
|
+
'x-correlation-id': 'correlation'
|
|
157
|
+
})
|
|
158
|
+
expect(second).toEqual({
|
|
159
|
+
authorization: 'Bearer service-token',
|
|
160
|
+
'x-correlation-id': 'caller'
|
|
161
|
+
})
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
test('it drops a caller authorization header in any casing', async () => {
|
|
165
|
+
// Arrange
|
|
166
|
+
const client = createClient()
|
|
167
|
+
vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
|
|
168
|
+
vi.spyOn(Wreck, 'read').mockResolvedValue({})
|
|
169
|
+
|
|
170
|
+
// Act
|
|
171
|
+
await client._get('api/cattle/UK123', {
|
|
172
|
+
headers: { Authorization: 'Bearer caller' }
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
// Assert
|
|
176
|
+
const { headers } = Wreck.request.mock.calls[0][2]
|
|
177
|
+
expect(headers.authorization).toBe('Bearer service-token')
|
|
178
|
+
expect(headers).not.toHaveProperty('Authorization')
|
|
133
179
|
})
|
|
180
|
+
|
|
181
|
+
test('it rejects without calling Wreck when the token cannot be obtained', async () => {
|
|
182
|
+
// Arrange
|
|
183
|
+
mocks.getServiceToken.mockRejectedValue(new Error('sts down'))
|
|
184
|
+
const client = createClient()
|
|
185
|
+
const request = vi.spyOn(Wreck, 'request')
|
|
186
|
+
|
|
187
|
+
// Act
|
|
188
|
+
let error
|
|
189
|
+
try {
|
|
190
|
+
await client._get('api/users/user-1/cphs')
|
|
191
|
+
} catch (e) {
|
|
192
|
+
error = e
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Assert
|
|
196
|
+
expect(error).toBeInstanceOf(ServiceTokenError)
|
|
197
|
+
expect(error.name).toBe('ServiceTokenError')
|
|
198
|
+
expect(error.statusCode).toBe(503)
|
|
199
|
+
expect(error.message).toBe(
|
|
200
|
+
'Failed to get a service token for lis-be4fe-cattle-home'
|
|
201
|
+
)
|
|
202
|
+
expect(error.cause.message).toBe('sts down')
|
|
203
|
+
expect(request).not.toHaveBeenCalled()
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
test('it ignores a caller-supplied baseUrl', async () => {
|
|
207
|
+
// Arrange
|
|
208
|
+
const client = createClient()
|
|
209
|
+
vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
|
|
210
|
+
vi.spyOn(Wreck, 'read').mockResolvedValue({})
|
|
211
|
+
|
|
212
|
+
// Act
|
|
213
|
+
await client._get('api/cattle/UK123', { baseUrl: 'https://evil.example' })
|
|
214
|
+
|
|
215
|
+
// Assert
|
|
216
|
+
expect(Wreck.request.mock.calls[0][2].baseUrl).toBe('http://localhost:8085')
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
test.each([['https://evil.example/steal'], ['//evil.example/steal']])(
|
|
220
|
+
'it rejects the absolute path %s without fetching a token or calling Wreck',
|
|
221
|
+
async (path) => {
|
|
222
|
+
// Arrange
|
|
223
|
+
mocks.getServiceToken.mockClear()
|
|
224
|
+
const client = createClient()
|
|
225
|
+
const request = vi.spyOn(Wreck, 'request')
|
|
226
|
+
|
|
227
|
+
// Act
|
|
228
|
+
let error
|
|
229
|
+
try {
|
|
230
|
+
await client._get(path)
|
|
231
|
+
} catch (e) {
|
|
232
|
+
error = e
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Assert
|
|
236
|
+
expect(error.message).toBe(
|
|
237
|
+
'BaseClient paths must be relative to the service base URL'
|
|
238
|
+
)
|
|
239
|
+
expect(mocks.getServiceToken).not.toHaveBeenCalled()
|
|
240
|
+
expect(request).not.toHaveBeenCalled()
|
|
241
|
+
}
|
|
242
|
+
)
|
|
134
243
|
})
|
|
135
244
|
|
|
136
245
|
describe('error handling', () => {
|
package/src/index.js
CHANGED
|
@@ -6,4 +6,4 @@ export * as requestContext from './request-context.js'
|
|
|
6
6
|
export { logger } from './logging/index.js'
|
|
7
7
|
export { createProxyPlugin } from './proxy-plugin.js'
|
|
8
8
|
export { getServiceBaseUrl } from './get-service-base-url.js'
|
|
9
|
-
export { BaseClient } from './base-client.js'
|
|
9
|
+
export { BaseClient, ServiceTokenError } from './base-client.js'
|
package/src/proxy-plugin.js
CHANGED
|
@@ -4,10 +4,26 @@ import { getModulesForHub } from '@defra/lis-hubs-infra-registry'
|
|
|
4
4
|
import { getServiceBaseUrl } from './get-service-base-url.js'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* @param {
|
|
7
|
+
* @param {string | undefined} cookieHeader
|
|
8
|
+
* @param {string} name
|
|
9
|
+
* @returns {string | undefined} the raw `name=value` pair, encoding untouched
|
|
10
|
+
*/
|
|
11
|
+
function findCookie(cookieHeader, name) {
|
|
12
|
+
return cookieHeader
|
|
13
|
+
?.split(';')
|
|
14
|
+
.map((cookie) => cookie.trim())
|
|
15
|
+
.find((cookie) => cookie.startsWith(`${name}=`))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{ hubId: string, environment: string, hubJwtCookieName: string }} options
|
|
8
20
|
* @returns {{ plugin: { name: string, register: Function } }}
|
|
9
21
|
*/
|
|
10
|
-
export function createProxyPlugin({ hubId, environment }) {
|
|
22
|
+
export function createProxyPlugin({ hubId, environment, hubJwtCookieName }) {
|
|
23
|
+
if (!hubJwtCookieName) {
|
|
24
|
+
throw new Error('hubJwtCookieName is required')
|
|
25
|
+
}
|
|
26
|
+
|
|
11
27
|
const modules = getModulesForHub(hubId).toSorted(
|
|
12
28
|
(a, b) => b.path.split('/').length - a.path.split('/').length
|
|
13
29
|
)
|
|
@@ -38,16 +54,22 @@ export function createProxyPlugin({ hubId, environment }) {
|
|
|
38
54
|
(subPath ? `${baseUri}/${subPath}` : baseUri) +
|
|
39
55
|
request.url.search
|
|
40
56
|
|
|
57
|
+
// passThrough copies request.headers itself and merges these
|
|
58
|
+
// headers on top, so a header can only be withheld from the
|
|
59
|
+
// spoke by removing it from the request. The spoke only gets
|
|
60
|
+
// the hub JWT cookie, never the hub's session or credentials.
|
|
61
|
+
const hubJwtCookie = findCookie(
|
|
62
|
+
request.headers.cookie,
|
|
63
|
+
hubJwtCookieName
|
|
64
|
+
)
|
|
65
|
+
delete request.headers.authorization
|
|
66
|
+
delete request.headers.cookie
|
|
67
|
+
|
|
41
68
|
return {
|
|
42
69
|
uri,
|
|
43
70
|
headers: {
|
|
44
71
|
'x-forwarded-prefix': path,
|
|
45
|
-
...(
|
|
46
|
-
authorization: request.headers.authorization
|
|
47
|
-
}),
|
|
48
|
-
...(request.headers.cookie && {
|
|
49
|
-
cookie: request.headers.cookie
|
|
50
|
-
})
|
|
72
|
+
...(hubJwtCookie && { cookie: hubJwtCookie })
|
|
51
73
|
}
|
|
52
74
|
}
|
|
53
75
|
}
|
package/src/proxy-plugin.test.js
CHANGED
|
@@ -28,7 +28,11 @@ describe('createProxyPlugin()', () => {
|
|
|
28
28
|
])('registers the %s proxy target', async (environment, expectedBaseUri) => {
|
|
29
29
|
// Arrange
|
|
30
30
|
const server = { route: vi.fn(), register: vi.fn() }
|
|
31
|
-
const proxy = createProxyPlugin({
|
|
31
|
+
const proxy = createProxyPlugin({
|
|
32
|
+
hubId: 'back-office',
|
|
33
|
+
environment,
|
|
34
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
35
|
+
})
|
|
32
36
|
|
|
33
37
|
// Act
|
|
34
38
|
await proxy.plugin.register(server)
|
|
@@ -44,15 +48,14 @@ describe('createProxyPlugin()', () => {
|
|
|
44
48
|
url: new URL('http://hub.test/cattle/summary-data'),
|
|
45
49
|
headers: {
|
|
46
50
|
authorization: 'Bearer hub-service-token',
|
|
47
|
-
cookie: '
|
|
51
|
+
cookie: 'livestock_hub_jwt=hub.jwt.value'
|
|
48
52
|
}
|
|
49
53
|
})
|
|
50
54
|
).toEqual({
|
|
51
55
|
uri: `${expectedBaseUri}/summary-data`,
|
|
52
56
|
headers: {
|
|
53
57
|
'x-forwarded-prefix': '/cattle',
|
|
54
|
-
|
|
55
|
-
cookie: 'session=abc'
|
|
58
|
+
cookie: 'livestock_hub_jwt=hub.jwt.value'
|
|
56
59
|
}
|
|
57
60
|
})
|
|
58
61
|
expect(
|
|
@@ -69,12 +72,97 @@ describe('createProxyPlugin()', () => {
|
|
|
69
72
|
})
|
|
70
73
|
})
|
|
71
74
|
|
|
75
|
+
test('forwards only the hub JWT cookie', async () => {
|
|
76
|
+
// Arrange
|
|
77
|
+
const server = { route: vi.fn(), register: vi.fn() }
|
|
78
|
+
const proxy = createProxyPlugin({
|
|
79
|
+
hubId: 'back-office',
|
|
80
|
+
environment: 'local',
|
|
81
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
82
|
+
})
|
|
83
|
+
const request = {
|
|
84
|
+
params: { path: 'animals' },
|
|
85
|
+
url: new URL('http://hub.test/cattle/animals'),
|
|
86
|
+
headers: {
|
|
87
|
+
cookie:
|
|
88
|
+
'front-office-session=abc; livestock_hub_jwt=hub.jwt.value; other=1'
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Act
|
|
93
|
+
await proxy.plugin.register(server)
|
|
94
|
+
const result = server.route.mock.calls[0][0].handler.proxy.mapUri(request)
|
|
95
|
+
|
|
96
|
+
// Assert
|
|
97
|
+
expect(result.headers.cookie).toBe('livestock_hub_jwt=hub.jwt.value')
|
|
98
|
+
expect(request.headers).toEqual({})
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
test('sends no cookie when there is no hub JWT cookie', async () => {
|
|
102
|
+
// Arrange
|
|
103
|
+
const server = { route: vi.fn(), register: vi.fn() }
|
|
104
|
+
const proxy = createProxyPlugin({
|
|
105
|
+
hubId: 'back-office',
|
|
106
|
+
environment: 'local',
|
|
107
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
108
|
+
})
|
|
109
|
+
const request = {
|
|
110
|
+
params: {},
|
|
111
|
+
url: new URL('http://hub.test/cattle'),
|
|
112
|
+
headers: { cookie: 'front-office-session=abc' }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Act
|
|
116
|
+
await proxy.plugin.register(server)
|
|
117
|
+
const result = server.route.mock.calls[0][0].handler.proxy.mapUri(request)
|
|
118
|
+
|
|
119
|
+
// Assert
|
|
120
|
+
expect(result.headers).toEqual({ 'x-forwarded-prefix': '/cattle' })
|
|
121
|
+
expect(request.headers).toEqual({})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
test('requires the hub JWT cookie name', () => {
|
|
125
|
+
// Arrange / Act
|
|
126
|
+
let error
|
|
127
|
+
try {
|
|
128
|
+
createProxyPlugin({ hubId: 'back-office', environment: 'local' })
|
|
129
|
+
} catch (e) {
|
|
130
|
+
error = e
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Assert
|
|
134
|
+
expect(error.message).toBe('hubJwtCookieName is required')
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
test('removes the inbound authorization header so passThrough cannot forward it', async () => {
|
|
138
|
+
// Arrange
|
|
139
|
+
const server = { route: vi.fn(), register: vi.fn() }
|
|
140
|
+
const proxy = createProxyPlugin({
|
|
141
|
+
hubId: 'back-office',
|
|
142
|
+
environment: 'local',
|
|
143
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
144
|
+
})
|
|
145
|
+
const request = {
|
|
146
|
+
params: { path: 'animals' },
|
|
147
|
+
url: new URL('http://hub.test/cattle/animals'),
|
|
148
|
+
headers: { authorization: 'Bearer browser-token', accept: 'text/html' }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Act
|
|
152
|
+
await proxy.plugin.register(server)
|
|
153
|
+
server.route.mock.calls[0][0].handler.proxy.mapUri(request)
|
|
154
|
+
|
|
155
|
+
// Assert
|
|
156
|
+
expect(request.headers).toEqual({ accept: 'text/html' })
|
|
157
|
+
})
|
|
158
|
+
|
|
72
159
|
test('forwards the incoming query string to the proxied service', async () => {
|
|
73
160
|
// Arrange
|
|
74
161
|
const server = { route: vi.fn(), register: vi.fn() }
|
|
75
162
|
const proxy = createProxyPlugin({
|
|
76
163
|
hubId: 'back-office',
|
|
77
|
-
environment: 'local'
|
|
164
|
+
environment: 'local',
|
|
165
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
78
166
|
})
|
|
79
167
|
|
|
80
168
|
// Act
|
|
@@ -100,7 +188,8 @@ describe('createProxyPlugin()', () => {
|
|
|
100
188
|
const server = { route: vi.fn(), register: vi.fn() }
|
|
101
189
|
const proxy = createProxyPlugin({
|
|
102
190
|
hubId: 'back-office',
|
|
103
|
-
environment: 'unknown'
|
|
191
|
+
environment: 'unknown',
|
|
192
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
104
193
|
})
|
|
105
194
|
|
|
106
195
|
// Act
|
|
@@ -125,7 +214,8 @@ describe('createProxyPlugin()', () => {
|
|
|
125
214
|
const server = { route: vi.fn(), register: vi.fn() }
|
|
126
215
|
const proxy = createProxyPlugin({
|
|
127
216
|
hubId: 'front-office',
|
|
128
|
-
environment: 'local'
|
|
217
|
+
environment: 'local',
|
|
218
|
+
hubJwtCookieName: 'livestock_hub_jwt'
|
|
129
219
|
})
|
|
130
220
|
|
|
131
221
|
// Act
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SIGNING_ALGORITHM = 'RS256'
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'
|
|
2
|
+
|
|
3
|
+
import { SIGNING_ALGORITHM } from './constants.js'
|
|
4
|
+
|
|
5
|
+
const DURATION_SECONDS = 900
|
|
6
|
+
const REFRESH_BEFORE_EXPIRY_SECONDS = 60
|
|
7
|
+
const MILLISECONDS_PER_SECOND = 1000
|
|
8
|
+
|
|
9
|
+
// The client lives for the process, as CDP's guide suggests for a global instance.
|
|
10
|
+
// The SDK has no timeouts by default and the token call sits in every
|
|
11
|
+
// proxied request's path.
|
|
12
|
+
const stsClient = new STSClient({
|
|
13
|
+
requestHandler: { connectionTimeout: 2000, requestTimeout: 3000 },
|
|
14
|
+
maxAttempts: 2
|
|
15
|
+
})
|
|
16
|
+
/** @type {Map<string, { token: string, expiresAt: number }>} */
|
|
17
|
+
const cache = new Map()
|
|
18
|
+
/** @type {Map<string, Promise<string>>} */
|
|
19
|
+
const inFlight = new Map()
|
|
20
|
+
|
|
21
|
+
async function fetchToken(audience) {
|
|
22
|
+
// Tags are deliberately omitted: they are rejected on CDP container roles.
|
|
23
|
+
const response = await stsClient.send(
|
|
24
|
+
new GetWebIdentityTokenCommand({
|
|
25
|
+
Audience: [audience],
|
|
26
|
+
DurationSeconds: DURATION_SECONDS,
|
|
27
|
+
SigningAlgorithm: SIGNING_ALGORITHM
|
|
28
|
+
})
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
if (!response?.WebIdentityToken) {
|
|
32
|
+
throw new Error('STS response did not include a WebIdentityToken')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const expiresAt = new Date(response.Expiration).getTime()
|
|
36
|
+
if (Number.isNaN(expiresAt)) {
|
|
37
|
+
throw new Error('STS response did not include a valid Expiration')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
cache.set(audience, { token: response.WebIdentityToken, expiresAt })
|
|
41
|
+
return response.WebIdentityToken
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} audience
|
|
46
|
+
* @returns {Promise<string>}
|
|
47
|
+
*/
|
|
48
|
+
export async function getServiceToken(audience) {
|
|
49
|
+
const cached = cache.get(audience)
|
|
50
|
+
const now = Date.now()
|
|
51
|
+
|
|
52
|
+
if (cached && now < cached.expiresAt) {
|
|
53
|
+
const refreshFrom =
|
|
54
|
+
cached.expiresAt - REFRESH_BEFORE_EXPIRY_SECONDS * MILLISECONDS_PER_SECOND
|
|
55
|
+
if (now >= refreshFrom) {
|
|
56
|
+
// Callers keep the still-valid token; a failure leaves it cached so a
|
|
57
|
+
// later call retries.
|
|
58
|
+
refreshToken(audience).catch(() => undefined)
|
|
59
|
+
}
|
|
60
|
+
return cached.token
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return refreshToken(audience)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function refreshToken(audience) {
|
|
67
|
+
const pending = inFlight.get(audience)
|
|
68
|
+
if (pending !== undefined) {
|
|
69
|
+
return pending
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const request = fetchTokenOnce(audience)
|
|
73
|
+
inFlight.set(audience, request)
|
|
74
|
+
return request
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function fetchTokenOnce(audience) {
|
|
78
|
+
try {
|
|
79
|
+
return await fetchToken(audience)
|
|
80
|
+
} finally {
|
|
81
|
+
inFlight.delete(audience)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { STSClient } from '@aws-sdk/client-sts'
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
|
3
|
+
|
|
4
|
+
vi.mock('@aws-sdk/client-sts', async (importOriginal) => ({
|
|
5
|
+
...(await importOriginal()),
|
|
6
|
+
STSClient: vi.fn()
|
|
7
|
+
}))
|
|
8
|
+
|
|
9
|
+
const NOW = new Date('2026-01-01T00:00:00Z')
|
|
10
|
+
|
|
11
|
+
function tokenResponse(token, secondsFromNow = 900) {
|
|
12
|
+
return {
|
|
13
|
+
WebIdentityToken: token,
|
|
14
|
+
Expiration: new Date(NOW.getTime() + secondsFromNow * 1000)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('getServiceToken()', () => {
|
|
19
|
+
let send
|
|
20
|
+
let getServiceToken
|
|
21
|
+
|
|
22
|
+
beforeEach(async () => {
|
|
23
|
+
vi.resetModules()
|
|
24
|
+
vi.useFakeTimers()
|
|
25
|
+
vi.setSystemTime(NOW)
|
|
26
|
+
send = vi.fn()
|
|
27
|
+
vi.mocked(STSClient).mockImplementation(function () {
|
|
28
|
+
this.send = send
|
|
29
|
+
})
|
|
30
|
+
;({ getServiceToken } = await import('./issuer.js'))
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
afterEach(() => {
|
|
34
|
+
vi.useRealTimers()
|
|
35
|
+
vi.clearAllMocks()
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test('builds one STS client, with request timeouts and limited attempts', async () => {
|
|
39
|
+
// Arrange
|
|
40
|
+
send.mockResolvedValue(tokenResponse('t1'))
|
|
41
|
+
|
|
42
|
+
// Act
|
|
43
|
+
await getServiceToken('aud-a')
|
|
44
|
+
await getServiceToken('aud-b')
|
|
45
|
+
|
|
46
|
+
// Assert
|
|
47
|
+
expect(STSClient).toHaveBeenCalledTimes(1)
|
|
48
|
+
expect(STSClient).toHaveBeenCalledWith({
|
|
49
|
+
requestHandler: { connectionTimeout: 2000, requestTimeout: 3000 },
|
|
50
|
+
maxAttempts: 2
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('requests a token for the audience with fixed options and no tags', async () => {
|
|
55
|
+
// Arrange
|
|
56
|
+
send.mockResolvedValueOnce(tokenResponse('t1'))
|
|
57
|
+
|
|
58
|
+
// Act
|
|
59
|
+
let result, error
|
|
60
|
+
try {
|
|
61
|
+
result = await getServiceToken('lis-apps-cattle-home')
|
|
62
|
+
} catch (e) {
|
|
63
|
+
error = e
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Assert
|
|
67
|
+
expect(error).toBeUndefined()
|
|
68
|
+
expect(result).toBe('t1')
|
|
69
|
+
expect(send).toHaveBeenCalledTimes(1)
|
|
70
|
+
expect(send.mock.calls[0][0].input).toEqual({
|
|
71
|
+
Audience: ['lis-apps-cattle-home'],
|
|
72
|
+
DurationSeconds: 900,
|
|
73
|
+
SigningAlgorithm: 'RS256'
|
|
74
|
+
})
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('reuses the cached token before the refresh window', async () => {
|
|
78
|
+
// Arrange
|
|
79
|
+
send.mockResolvedValueOnce(tokenResponse('t1'))
|
|
80
|
+
await getServiceToken('aud')
|
|
81
|
+
vi.setSystemTime(new Date(NOW.getTime() + 839 * 1000))
|
|
82
|
+
|
|
83
|
+
// Act
|
|
84
|
+
const result = await getServiceToken('aud')
|
|
85
|
+
|
|
86
|
+
// Assert
|
|
87
|
+
expect(result).toBe('t1')
|
|
88
|
+
expect(send).toHaveBeenCalledTimes(1)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('returns the cached token inside the refresh window and refreshes in the background', async () => {
|
|
92
|
+
// Arrange
|
|
93
|
+
send
|
|
94
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
95
|
+
.mockReturnValueOnce(new Promise(() => undefined))
|
|
96
|
+
await getServiceToken('aud')
|
|
97
|
+
vi.setSystemTime(new Date(NOW.getTime() + 840 * 1000))
|
|
98
|
+
|
|
99
|
+
// Act
|
|
100
|
+
const result = await getServiceToken('aud')
|
|
101
|
+
|
|
102
|
+
// Assert
|
|
103
|
+
expect(result).toBe('t1')
|
|
104
|
+
expect(send).toHaveBeenCalledTimes(2)
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
test('triggers a single background refresh for concurrent calls inside the window', async () => {
|
|
108
|
+
// Arrange
|
|
109
|
+
send
|
|
110
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
111
|
+
.mockReturnValueOnce(new Promise(() => undefined))
|
|
112
|
+
await getServiceToken('aud')
|
|
113
|
+
vi.setSystemTime(new Date(NOW.getTime() + 840 * 1000))
|
|
114
|
+
|
|
115
|
+
// Act
|
|
116
|
+
const results = await Promise.all([
|
|
117
|
+
getServiceToken('aud'),
|
|
118
|
+
getServiceToken('aud')
|
|
119
|
+
])
|
|
120
|
+
|
|
121
|
+
// Assert
|
|
122
|
+
expect(results).toEqual(['t1', 't1'])
|
|
123
|
+
expect(send).toHaveBeenCalledTimes(2)
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test('returns the new token on the call after a successful background refresh', async () => {
|
|
127
|
+
// Arrange
|
|
128
|
+
send
|
|
129
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
130
|
+
.mockResolvedValueOnce(tokenResponse('t2', 1800))
|
|
131
|
+
await getServiceToken('aud')
|
|
132
|
+
vi.setSystemTime(new Date(NOW.getTime() + 840 * 1000))
|
|
133
|
+
await getServiceToken('aud')
|
|
134
|
+
await vi.advanceTimersByTimeAsync(0)
|
|
135
|
+
|
|
136
|
+
// Act
|
|
137
|
+
const result = await getServiceToken('aud')
|
|
138
|
+
|
|
139
|
+
// Assert
|
|
140
|
+
expect(result).toBe('t2')
|
|
141
|
+
expect(send).toHaveBeenCalledTimes(2)
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
test('keeps serving the cached token when a background refresh fails and retries on the next call', async () => {
|
|
145
|
+
// Arrange
|
|
146
|
+
send
|
|
147
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
148
|
+
.mockRejectedValueOnce(new Error('sts down'))
|
|
149
|
+
.mockResolvedValueOnce(tokenResponse('t2', 1800))
|
|
150
|
+
await getServiceToken('aud')
|
|
151
|
+
vi.setSystemTime(new Date(NOW.getTime() + 840 * 1000))
|
|
152
|
+
const duringFailure = await getServiceToken('aud')
|
|
153
|
+
await vi.advanceTimersByTimeAsync(0)
|
|
154
|
+
|
|
155
|
+
// Act
|
|
156
|
+
const afterFailure = await getServiceToken('aud')
|
|
157
|
+
await vi.advanceTimersByTimeAsync(0)
|
|
158
|
+
const afterRetry = await getServiceToken('aud')
|
|
159
|
+
|
|
160
|
+
// Assert
|
|
161
|
+
expect(duringFailure).toBe('t1')
|
|
162
|
+
expect(afterFailure).toBe('t1')
|
|
163
|
+
expect(afterRetry).toBe('t2')
|
|
164
|
+
expect(send).toHaveBeenCalledTimes(3)
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
test('caches tokens separately per audience', async () => {
|
|
168
|
+
// Arrange
|
|
169
|
+
send
|
|
170
|
+
.mockResolvedValueOnce(tokenResponse('token-a'))
|
|
171
|
+
.mockResolvedValueOnce(tokenResponse('token-b'))
|
|
172
|
+
|
|
173
|
+
// Act
|
|
174
|
+
const first = await getServiceToken('aud-a')
|
|
175
|
+
const second = await getServiceToken('aud-b')
|
|
176
|
+
const firstAgain = await getServiceToken('aud-a')
|
|
177
|
+
|
|
178
|
+
// Assert
|
|
179
|
+
expect(first).toBe('token-a')
|
|
180
|
+
expect(second).toBe('token-b')
|
|
181
|
+
expect(firstAgain).toBe('token-a')
|
|
182
|
+
expect(send).toHaveBeenCalledTimes(2)
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
test('shares one in-flight request between concurrent calls for an audience', async () => {
|
|
186
|
+
// Arrange
|
|
187
|
+
send.mockResolvedValueOnce(tokenResponse('t1'))
|
|
188
|
+
|
|
189
|
+
// Act
|
|
190
|
+
const results = await Promise.all([
|
|
191
|
+
getServiceToken('aud'),
|
|
192
|
+
getServiceToken('aud')
|
|
193
|
+
])
|
|
194
|
+
|
|
195
|
+
// Assert
|
|
196
|
+
expect(results).toEqual(['t1', 't1'])
|
|
197
|
+
expect(send).toHaveBeenCalledTimes(1)
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
test('does not cache a failed request so the next call retries', async () => {
|
|
201
|
+
// Arrange
|
|
202
|
+
send
|
|
203
|
+
.mockRejectedValueOnce(new Error('sts down'))
|
|
204
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
205
|
+
|
|
206
|
+
// Act
|
|
207
|
+
let firstError
|
|
208
|
+
try {
|
|
209
|
+
await getServiceToken('aud')
|
|
210
|
+
} catch (e) {
|
|
211
|
+
firstError = e
|
|
212
|
+
}
|
|
213
|
+
const result = await getServiceToken('aud')
|
|
214
|
+
|
|
215
|
+
// Assert
|
|
216
|
+
expect(firstError.message).toBe('sts down')
|
|
217
|
+
expect(result).toBe('t1')
|
|
218
|
+
expect(send).toHaveBeenCalledTimes(2)
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
test('rejects when the refresh of an expired token fails', async () => {
|
|
222
|
+
// Arrange
|
|
223
|
+
send
|
|
224
|
+
.mockResolvedValueOnce(tokenResponse('t1'))
|
|
225
|
+
.mockRejectedValueOnce(new Error('sts down'))
|
|
226
|
+
await getServiceToken('aud')
|
|
227
|
+
vi.setSystemTime(new Date(NOW.getTime() + 900 * 1000))
|
|
228
|
+
|
|
229
|
+
// Act
|
|
230
|
+
let error
|
|
231
|
+
try {
|
|
232
|
+
await getServiceToken('aud')
|
|
233
|
+
} catch (e) {
|
|
234
|
+
error = e
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Assert
|
|
238
|
+
expect(error.message).toBe('sts down')
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
test('throws when the response has an invalid Expiration', async () => {
|
|
242
|
+
// Arrange
|
|
243
|
+
send.mockResolvedValueOnce({
|
|
244
|
+
WebIdentityToken: 't1',
|
|
245
|
+
Expiration: 'not a date'
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
// Act
|
|
249
|
+
let error
|
|
250
|
+
try {
|
|
251
|
+
await getServiceToken('aud')
|
|
252
|
+
} catch (e) {
|
|
253
|
+
error = e
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Assert
|
|
257
|
+
expect(error.message).toBe(
|
|
258
|
+
'STS response did not include a valid Expiration'
|
|
259
|
+
)
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
test.each([[{}], [undefined]])(
|
|
263
|
+
'throws when the response has no WebIdentityToken (%j)',
|
|
264
|
+
async (response) => {
|
|
265
|
+
// Arrange
|
|
266
|
+
send.mockResolvedValueOnce(response)
|
|
267
|
+
|
|
268
|
+
// Act
|
|
269
|
+
let error
|
|
270
|
+
try {
|
|
271
|
+
await getServiceToken('aud')
|
|
272
|
+
} catch (e) {
|
|
273
|
+
error = e
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Assert
|
|
277
|
+
expect(error.message).toBe(
|
|
278
|
+
'STS response did not include a WebIdentityToken'
|
|
279
|
+
)
|
|
280
|
+
}
|
|
281
|
+
)
|
|
282
|
+
})
|