@defra/lis-hubs-infra-core 0.13.0 → 0.14.0

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-core",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -7,6 +7,7 @@ import { getServiceToken } from './service-token/issuer.js'
7
7
  const BAD_REQUEST = 400
8
8
  const UNPROCESSABLE_ENTITY = 422
9
9
  const SERVICE_UNAVAILABLE = 503
10
+ const DEFAULT_TIMEOUT_MS = 3000
10
11
 
11
12
  const ABSOLUTE_URL_PATTERN = /^([a-z][a-z0-9+.-]*:|\/\/)/i
12
13
 
@@ -29,15 +30,25 @@ export class BaseClient {
29
30
  /** @protected */
30
31
  _serviceName
31
32
 
33
+ /** @protected */
34
+ _apiKey
35
+
32
36
  /** @protected */
33
37
  _timeout
34
38
 
35
39
  /**
36
- * @param {{ environment: string, serviceName: string, port?: number, timeout?: number }} options
40
+ * @param {{ environment: string, serviceName: string, port?: number, apiKey?: string, timeout?: number }} options timeout is in milliseconds, default 3000, and applies to each of the response and body reads
37
41
  */
38
- constructor({ environment, serviceName, port, timeout }) {
42
+ constructor({
43
+ environment,
44
+ serviceName,
45
+ port,
46
+ apiKey,
47
+ timeout = DEFAULT_TIMEOUT_MS
48
+ }) {
39
49
  this._baseUrl = getServiceBaseUrl(environment, serviceName, port).origin
40
50
  this._serviceName = serviceName
51
+ this._apiKey = apiKey
41
52
  this._timeout = timeout
42
53
  }
43
54
 
@@ -109,31 +120,36 @@ export class BaseClient {
109
120
  /**
110
121
  * @protected
111
122
  * @param {object} [callerHeaders] headers supplied on this call
112
- * @returns {Promise<object>} correlation, caller and service token headers merged
123
+ * @returns {Promise<object>} correlation, api key, caller and service token headers merged
113
124
  */
114
- async _buildHeaders(callerHeaders) {
125
+ async _buildHeaders(callerHeaders = {}) {
115
126
  const headers = { ...requestContext.getHeaders() }
116
-
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
- }
126
-
127
- async #getAuthorization() {
127
+ let authorizationToken
128
128
  try {
129
- const token = await getServiceToken(this._serviceName)
130
- return `Bearer ${token}`
129
+ authorizationToken = await getServiceToken(this._serviceName)
131
130
  } catch (cause) {
132
131
  throw new ServiceTokenError(
133
132
  `Failed to get a service token for ${this._serviceName}`,
134
133
  { cause }
135
134
  )
136
135
  }
136
+
137
+ headers['authorization'] = `Bearer ${authorizationToken}`
138
+
139
+ if (this._apiKey) {
140
+ headers['x-api-key'] = this._apiKey
141
+ }
142
+
143
+ for (const [key, value] of Object.entries(callerHeaders)) {
144
+ if (
145
+ key.toLowerCase() !== 'authorization' &&
146
+ key.toLowerCase() !== 'x-api-key'
147
+ ) {
148
+ headers[key] = value
149
+ }
150
+ }
151
+
152
+ return headers
137
153
  }
138
154
 
139
155
  /**
@@ -96,6 +96,60 @@ describe('request verbs', () => {
96
96
  }
97
97
  )
98
98
 
99
+ test('it sends the api key in the x-api-key header', async () => {
100
+ // Arrange
101
+ const client = createClient({ apiKey: 'test-api-key' })
102
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
103
+ vi.spyOn(Wreck, 'read').mockResolvedValue({})
104
+
105
+ // Act
106
+ await client._get('api/users/user-1/cphs')
107
+
108
+ // Assert
109
+ expect(Wreck.request.mock.calls[0][2].headers).toEqual({
110
+ 'x-correlation-id': 'correlation-1',
111
+ 'x-cdp-request-id': 'correlation-1',
112
+ 'x-api-key': 'test-api-key',
113
+ authorization: 'Bearer service-token'
114
+ })
115
+ })
116
+
117
+ test('it times requests out after 3 seconds by default', async () => {
118
+ // Arrange
119
+ const client = createClient()
120
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
121
+ vi.spyOn(Wreck, 'read').mockResolvedValue({})
122
+
123
+ // Act
124
+ await client._get('api/users/user-1/cphs')
125
+
126
+ // Assert
127
+ expect(Wreck.request.mock.calls[0][2].timeout).toBe(3000)
128
+ })
129
+
130
+ test.each([
131
+ ['without a configured api key', undefined],
132
+ ['over a configured api key', 'test-api-key']
133
+ ])(
134
+ 'it never sends a caller-supplied x-api-key, in any casing, %s',
135
+ async (_, apiKey) => {
136
+ // Arrange
137
+ const client = createClient({ apiKey })
138
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
139
+ vi.spyOn(Wreck, 'read').mockResolvedValue({})
140
+
141
+ // Act
142
+ await client._get('api/users/user-1/cphs', {
143
+ headers: { 'X-Api-Key': 'caller-key', 'x-api-key': 'caller-key' }
144
+ })
145
+
146
+ // Assert
147
+ const { headers } = Wreck.request.mock.calls[0][2]
148
+ expect(headers).not.toHaveProperty('X-Api-Key')
149
+ expect(headers['x-api-key']).toBe(apiKey)
150
+ }
151
+ )
152
+
99
153
  test('it lets per-call headers override the defaults', async () => {
100
154
  // Arrange
101
155
  const client = createClient()
@@ -131,20 +185,25 @@ describe('service token', () => {
131
185
  )
132
186
  })
133
187
 
134
- test('it applies correlation, caller then service token headers in that order', async () => {
188
+ test('it applies correlation, then caller headers, with the api key and service token taking precedence', async () => {
135
189
  // Arrange
136
190
  mocks.requestContextGetHeaders.mockReturnValue({
137
191
  authorization: 'Bearer correlation',
192
+ 'x-api-key': 'correlation',
138
193
  'x-correlation-id': 'correlation'
139
194
  })
140
- const client = createClient()
195
+ const client = createClient({ apiKey: 'test-api-key' })
141
196
  vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
142
197
  vi.spyOn(Wreck, 'read').mockResolvedValue({})
143
198
 
144
199
  // Act
145
200
  await client._get('api/cattle/UK123')
146
201
  await client._get('api/cattle/UK123', {
147
- headers: { authorization: 'Bearer caller', 'x-correlation-id': 'caller' }
202
+ headers: {
203
+ authorization: 'Bearer caller',
204
+ 'x-api-key': 'caller',
205
+ 'x-correlation-id': 'caller'
206
+ }
148
207
  })
149
208
 
150
209
  // Assert
@@ -153,10 +212,12 @@ describe('service token', () => {
153
212
  )
154
213
  expect(first).toEqual({
155
214
  authorization: 'Bearer service-token',
215
+ 'x-api-key': 'test-api-key',
156
216
  'x-correlation-id': 'correlation'
157
217
  })
158
218
  expect(second).toEqual({
159
219
  authorization: 'Bearer service-token',
220
+ 'x-api-key': 'test-api-key',
160
221
  'x-correlation-id': 'caller'
161
222
  })
162
223
  })
@@ -2,7 +2,9 @@ import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'
2
2
 
3
3
  import { SIGNING_ALGORITHM } from './constants.js'
4
4
 
5
- const DURATION_SECONDS = 900
5
+ const MAX_DURATION_SECONDS = 900
6
+ const MIN_DURATION_SECONDS = 60
7
+ const SESSION_EXPIRY_MARGIN_SECONDS = 60
6
8
  const REFRESH_BEFORE_EXPIRY_SECONDS = 60
7
9
  const MILLISECONDS_PER_SECOND = 1000
8
10
 
@@ -18,12 +20,38 @@ const cache = new Map()
18
20
  /** @type {Map<string, Promise<string>>} */
19
21
  const inFlight = new Map()
20
22
 
23
+ /**
24
+ * A token can't outlive the role session that requests it (STS rejects that
25
+ * with SessionDurationEscalation), and the SDK keeps credentials until they
26
+ * are 5 minutes from expiry, so the duration is capped by the time the
27
+ * current credentials have left.
28
+ *
29
+ * @returns {Promise<number>}
30
+ */
31
+ async function getTokenDurationSeconds() {
32
+ const { expiration } = await stsClient.config.credentials()
33
+ if (!expiration) {
34
+ return MAX_DURATION_SECONDS
35
+ }
36
+
37
+ const secondsLeft =
38
+ Math.floor((expiration.getTime() - Date.now()) / MILLISECONDS_PER_SECOND) -
39
+ SESSION_EXPIRY_MARGIN_SECONDS
40
+ if (secondsLeft < MIN_DURATION_SECONDS) {
41
+ throw new Error(
42
+ 'The role session expires too soon to issue a service token'
43
+ )
44
+ }
45
+
46
+ return Math.min(MAX_DURATION_SECONDS, secondsLeft)
47
+ }
48
+
21
49
  async function fetchToken(audience) {
22
50
  // Tags are deliberately omitted: they are rejected on CDP container roles.
23
51
  const response = await stsClient.send(
24
52
  new GetWebIdentityTokenCommand({
25
53
  Audience: [audience],
26
- DurationSeconds: DURATION_SECONDS,
54
+ DurationSeconds: await getTokenDurationSeconds(),
27
55
  SigningAlgorithm: SIGNING_ALGORITHM
28
56
  })
29
57
  )
@@ -8,6 +8,9 @@ vi.mock('@aws-sdk/client-sts', async (importOriginal) => ({
8
8
 
9
9
  const NOW = new Date('2026-01-01T00:00:00Z')
10
10
 
11
+ // Lets background work queued on resolved promises run.
12
+ const flushPromises = () => new Promise((resolve) => process.nextTick(resolve))
13
+
11
14
  function tokenResponse(token, secondsFromNow = 900) {
12
15
  return {
13
16
  WebIdentityToken: token,
@@ -17,6 +20,7 @@ function tokenResponse(token, secondsFromNow = 900) {
17
20
 
18
21
  describe('getServiceToken()', () => {
19
22
  let send
23
+ let credentials
20
24
  let getServiceToken
21
25
 
22
26
  beforeEach(async () => {
@@ -24,8 +28,10 @@ describe('getServiceToken()', () => {
24
28
  vi.useFakeTimers()
25
29
  vi.setSystemTime(NOW)
26
30
  send = vi.fn()
31
+ credentials = vi.fn().mockResolvedValue({})
27
32
  vi.mocked(STSClient).mockImplementation(function () {
28
33
  this.send = send
34
+ this.config = { credentials }
29
35
  })
30
36
  ;({ getServiceToken } = await import('./issuer.js'))
31
37
  })
@@ -74,6 +80,61 @@ describe('getServiceToken()', () => {
74
80
  })
75
81
  })
76
82
 
83
+ test.each([
84
+ ['credentials with no expiry', undefined, 900],
85
+ ['credentials with an hour left', 3600, 900],
86
+ ['credentials 10 minutes from expiry', 600, 540],
87
+ ['credentials 5 minutes from expiry', 300, 240]
88
+ ])(
89
+ 'requests a duration that ends before the role session, for %s',
90
+ async (_, credentialsSecondsLeft, expectedDuration) => {
91
+ // Arrange
92
+ credentials.mockResolvedValue(
93
+ credentialsSecondsLeft === undefined
94
+ ? {}
95
+ : {
96
+ expiration: new Date(
97
+ NOW.getTime() + credentialsSecondsLeft * 1000
98
+ )
99
+ }
100
+ )
101
+ send.mockResolvedValueOnce(tokenResponse('t1', expectedDuration))
102
+
103
+ // Act
104
+ await getServiceToken('lis-apps-cattle-home')
105
+
106
+ // Assert
107
+ expect(send.mock.calls[0][0].input.DurationSeconds).toBe(expectedDuration)
108
+ }
109
+ )
110
+
111
+ test.each([
112
+ ['expires too soon', 119],
113
+ ['has already expired', -30]
114
+ ])(
115
+ 'rejects without calling STS when the role session %s',
116
+ async (_, credentialsSecondsLeft) => {
117
+ // Arrange
118
+ credentials.mockResolvedValue({
119
+ expiration: new Date(NOW.getTime() + credentialsSecondsLeft * 1000)
120
+ })
121
+
122
+ // Act
123
+ let error
124
+ try {
125
+ await getServiceToken('lis-apps-cattle-home')
126
+ } catch (e) {
127
+ error = e
128
+ }
129
+
130
+ // Assert
131
+ expect(error.message).toBe(
132
+ 'The role session expires too soon to issue a service token'
133
+ )
134
+ expect(send).not.toHaveBeenCalled()
135
+ }
136
+ )
137
+
77
138
  test('reuses the cached token before the refresh window', async () => {
78
139
  // Arrange
79
140
  send.mockResolvedValueOnce(tokenResponse('t1'))
@@ -98,6 +159,7 @@ describe('getServiceToken()', () => {
98
159
 
99
160
  // Act
100
161
  const result = await getServiceToken('aud')
162
+ await flushPromises()
101
163
 
102
164
  // Assert
103
165
  expect(result).toBe('t1')