@defra/lis-hubs-infra-core 0.21.0 → 0.22.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/README.md CHANGED
@@ -111,15 +111,19 @@ Locally, lis-dev's `lis-fake-sts` service stands in for AWS STS. See
111
111
 
112
112
  `createProxyPlugin` is used by hubs. It registers a proxy route for every module that
113
113
  `@defra/lis-hubs-infra-registry` lists for the hub, forwarding requests to that module's spoke and
114
- forwarding only the hub JWT cookie, never the hub session cookie or the `Authorization` header.
114
+ forwarding only the hub JWT cookie and any cookies named in `forwardedCookieNames` (for example
115
+ the cookie consent choice, which the spoke's layout needs to decide whether to show the banner),
116
+ never the hub session cookie or the `Authorization` header.
115
117
 
116
118
  ```js
117
119
  import { createProxyPlugin } from '@defra/lis-hubs-infra-core'
120
+ import { COOKIES_POLICY_COOKIE_NAME } from '@defra/lis-infra-ui-services/cookies/cookies-policy'
118
121
 
119
122
  const proxy = createProxyPlugin({
120
123
  hubId: 'front-office',
121
124
  environment: config.get('environment'),
122
- hubJwtCookieName: config.get('auth.hubJwt.cookieName')
125
+ hubJwtCookieName: config.get('auth.hubJwt.cookieName'),
126
+ forwardedCookieNames: [COOKIES_POLICY_COOKIE_NAME] // optional, none by default
123
127
  })
124
128
 
125
129
  await server.register(proxy.plugin)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-core",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -6,24 +6,43 @@ import { getServiceToken } from './service-token/issuer.js'
6
6
 
7
7
  /**
8
8
  * @param {string | undefined} cookieHeader
9
- * @param {string} name
10
- * @returns {string | undefined} the raw `name=value` pair, encoding untouched
9
+ * @param {string[]} names
10
+ * @returns {string | undefined} a cookie header of the named cookies that are present, in the browser's order, raw `name=value` pairs with encoding untouched
11
11
  */
12
- function findCookie(cookieHeader, name) {
13
- return cookieHeader
12
+ function pickCookies(cookieHeader, names) {
13
+ const picked = cookieHeader
14
14
  ?.split(';')
15
15
  .map((cookie) => cookie.trim())
16
- .find((cookie) => cookie.startsWith(`${name}=`))
16
+ .filter((cookie) => names.some((name) => cookie.startsWith(`${name}=`)))
17
+
18
+ return picked?.length ? picked.join('; ') : undefined
17
19
  }
18
20
 
19
21
  /**
20
- * @param {{ hubId: string, environment: string, hubJwtCookieName: string }} options
22
+ * @param {object} options
23
+ * @param {string} options.hubId
24
+ * @param {string} options.environment
25
+ * @param {string} options.hubJwtCookieName - the cookie that identifies the user to the spoke
26
+ * @param {string[]} [options.forwardedCookieNames] - other browser cookies the spoke may see, such as the cookie consent choice; none by default
21
27
  * @returns {{ plugin: { name: string, register: Function } }}
22
28
  */
23
- export function createProxyPlugin({ hubId, environment, hubJwtCookieName }) {
29
+ export function createProxyPlugin({
30
+ hubId,
31
+ environment,
32
+ hubJwtCookieName,
33
+ forwardedCookieNames = []
34
+ }) {
24
35
  if (!hubJwtCookieName) {
25
36
  throw new Error('hubJwtCookieName is required')
26
37
  }
38
+ if (
39
+ !Array.isArray(forwardedCookieNames) ||
40
+ forwardedCookieNames.some((name) => typeof name !== 'string' || !name)
41
+ ) {
42
+ throw new Error('forwardedCookieNames must be an array of cookie names')
43
+ }
44
+
45
+ const cookieNames = [hubJwtCookieName, ...forwardedCookieNames]
27
46
 
28
47
  const modules = getModulesForHub(hubId).toSorted(
29
48
  (a, b) => b.path.split('/').length - a.path.split('/').length
@@ -59,10 +78,11 @@ export function createProxyPlugin({ hubId, environment, hubJwtCookieName }) {
59
78
  // passThrough copies request.headers itself and merges these
60
79
  // headers on top, so a header can only be withheld from the
61
80
  // spoke by removing it from the request. The spoke only gets
62
- // the hub JWT cookie, never the hub's session or credentials.
63
- const hubJwtCookie = findCookie(
81
+ // the hub JWT cookie and the cookies named as forwarded,
82
+ // never the hub's session or credentials.
83
+ const forwardedCookies = pickCookies(
64
84
  request.headers.cookie,
65
- hubJwtCookieName
85
+ cookieNames
66
86
  )
67
87
  delete request.headers.authorization
68
88
  delete request.headers.cookie
@@ -72,7 +92,7 @@ export function createProxyPlugin({ hubId, environment, hubJwtCookieName }) {
72
92
  headers: {
73
93
  'x-forwarded-prefix': path,
74
94
  authorization: `Bearer ${await getServiceToken(serviceName)}`,
75
- ...(hubJwtCookie && { cookie: hubJwtCookie })
95
+ ...(forwardedCookies && { cookie: forwardedCookies })
76
96
  }
77
97
  }
78
98
  }
@@ -156,6 +156,85 @@ describe('createProxyPlugin()', () => {
156
156
  expect(request.headers).toEqual({})
157
157
  })
158
158
 
159
+ test('forwards the named cookies alongside the hub JWT, in the browser order', async () => {
160
+ // Arrange
161
+ const server = { route: vi.fn(), register: vi.fn() }
162
+ const proxy = createProxyPlugin({
163
+ hubId: 'back-office',
164
+ environment: 'local',
165
+ hubJwtCookieName: 'livestock_hub_jwt',
166
+ forwardedCookieNames: ['cookies_policy']
167
+ })
168
+ const request = {
169
+ params: { path: 'animals' },
170
+ url: new URL('http://hub.test/cattle/animals'),
171
+ headers: {
172
+ cookie:
173
+ 'cookies_policy=%7B%22analytics%22%3Afalse%7D; front-office-session=abc; livestock_hub_jwt=hub.jwt.value'
174
+ }
175
+ }
176
+
177
+ // Act
178
+ await proxy.plugin.register(server)
179
+ const result =
180
+ await server.route.mock.calls[0][0].handler.proxy.mapUri(request)
181
+
182
+ // Assert
183
+ expect(result.headers.cookie).toBe(
184
+ 'cookies_policy=%7B%22analytics%22%3Afalse%7D; livestock_hub_jwt=hub.jwt.value'
185
+ )
186
+ expect(request.headers).toEqual({})
187
+ })
188
+
189
+ test('forwards a named cookie on its own when there is no hub JWT cookie', async () => {
190
+ // Arrange
191
+ const server = { route: vi.fn(), register: vi.fn() }
192
+ const proxy = createProxyPlugin({
193
+ hubId: 'back-office',
194
+ environment: 'local',
195
+ hubJwtCookieName: 'livestock_hub_jwt',
196
+ forwardedCookieNames: ['cookies_policy']
197
+ })
198
+ const request = {
199
+ params: {},
200
+ url: new URL('http://hub.test/cattle'),
201
+ headers: { cookie: 'front-office-session=abc; cookies_policy=x' }
202
+ }
203
+
204
+ // Act
205
+ await proxy.plugin.register(server)
206
+ const result =
207
+ await server.route.mock.calls[0][0].handler.proxy.mapUri(request)
208
+
209
+ // Assert
210
+ expect(result.headers.cookie).toBe('cookies_policy=x')
211
+ })
212
+
213
+ test.each([['not an array'], [[42]], [['']]])(
214
+ 'rejects forwardedCookieNames %j',
215
+ (forwardedCookieNames) => {
216
+ // Arrange
217
+ let error
218
+
219
+ // Act
220
+ try {
221
+ createProxyPlugin({
222
+ hubId: 'back-office',
223
+ environment: 'local',
224
+ hubJwtCookieName: 'livestock_hub_jwt',
225
+ forwardedCookieNames
226
+ })
227
+ } catch (e) {
228
+ error = e
229
+ }
230
+
231
+ // Assert
232
+ expect(error.message).toBe(
233
+ 'forwardedCookieNames must be an array of cookie names'
234
+ )
235
+ }
236
+ )
237
+
159
238
  test('sends no cookie when there is no hub JWT cookie', async () => {
160
239
  // Arrange
161
240
  const server = { route: vi.fn(), register: vi.fn() }