@defra/lis-hubs-infra-core 0.3.0 → 0.4.0-lreg-432.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0-lreg-432.alpha.2",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -32,18 +32,18 @@
32
32
  "license": "OGL-UK-3.0",
33
33
  "dependencies": {
34
34
  "@defra/lis-hubs-infra-registry": "^0.3.0",
35
+ "@elastic/ecs-pino-format": "1.5.0",
35
36
  "@hapi/h2o2": "10.0.4",
36
- "convict": "6.2.5",
37
- "convict-format-with-validator": "6.2.0",
38
- "eslint-plugin-jsdoc": "^63.0.8",
39
- "eslint-plugin-sonarjs": "^4.1.0",
40
- "neostandard": "0.13.0"
37
+ "hapi-pino": "13.0.0",
38
+ "pino": "10.1.0",
39
+ "pino-pretty": "13.1.3"
41
40
  },
42
41
  "peerDependencies": {
43
42
  "eslint": "^9.0.0"
44
43
  },
45
44
  "devDependencies": {
46
45
  "@defra/lis-infra-eslint-config": "^0.6.0",
46
+ "@types/node": "^26.4.0",
47
47
  "@vitest/coverage-istanbul": "^4.1.10",
48
48
  "audit-ci": "^7.1.0",
49
49
  "eslint": "^9.0.0",
package/src/index.js CHANGED
@@ -3,4 +3,6 @@ export const HUB_TYPES = ['front-office', 'back-office']
3
3
  export const HUB_CORE_STATUS = 'scaffolded'
4
4
 
5
5
  export * as requestContext from './request-context.js'
6
+ export { logger } from './logging/index.js'
6
7
  export { createProxyPlugin } from './proxy-plugin.js'
8
+ export { derivePseudonymousUserId } from './pseudonymous-user-id.js'
@@ -0,0 +1,129 @@
1
+ /** @import { Logger } from 'pino' */
2
+ import hapiPino from 'hapi-pino'
3
+ import { TogglablePrettyStream } from './togglable-pretty-stream.js'
4
+ import { pino } from 'pino'
5
+ import { ecsFormat } from '@elastic/ecs-pino-format'
6
+ import { mixin } from './mixin.js'
7
+
8
+ const defaultIgnorePath = (_, request) =>
9
+ request.path.startsWith('/public') ||
10
+ request.path === '/health' ||
11
+ request.path === '/favicon.ico'
12
+
13
+ const validFormats = ['ecs', 'pretty-print']
14
+
15
+ // Standardised, non-configurable across every consumer - these headers
16
+ // must never reach logs.
17
+ const redactPaths = [
18
+ 'req.headers.authorization',
19
+ 'req.headers.cookie',
20
+ 'res.headers'
21
+ ]
22
+
23
+ class Logger {
24
+ #logger
25
+ #prettyStream
26
+ #level = 'info'
27
+ #enabled = true
28
+ #format = 'ecs'
29
+ #serviceName = process.env.SERVICE_NAME
30
+ #serviceVersion = process.env.SERVICE_VERSION
31
+
32
+ constructor() {
33
+ this.#prettyStream = new TogglablePrettyStream({ sync: true })
34
+ this.#logger = pino(
35
+ {
36
+ ...ecsFormat(),
37
+ redact: { paths: redactPaths, remove: true },
38
+ level: 'info',
39
+ nesting: true,
40
+ mixin: () => ({
41
+ ...mixin(),
42
+ service: { name: this.#serviceName, version: this.#serviceVersion }
43
+ })
44
+ },
45
+ this.#prettyStream
46
+ )
47
+ }
48
+
49
+ set serviceName(name) {
50
+ this.#serviceName = name
51
+ }
52
+
53
+ get serviceName() {
54
+ return this.#serviceName
55
+ }
56
+
57
+ set serviceVersion(version) {
58
+ this.#serviceVersion = version
59
+ }
60
+
61
+ get serviceVersion() {
62
+ return this.#serviceVersion
63
+ }
64
+
65
+ set level(level) {
66
+ this.#level = level
67
+ this.#logger.level = this.#enabled ? this.#level : 'silent'
68
+ }
69
+
70
+ get level() {
71
+ return this.#level
72
+ }
73
+
74
+ set enabled(bool) {
75
+ this.#enabled = bool
76
+ this.#logger.level = bool ? this.#level : 'silent'
77
+ }
78
+
79
+ get enabled() {
80
+ return this.#enabled
81
+ }
82
+
83
+ set format(str) {
84
+ if (validFormats.includes(str)) {
85
+ this.#format = str
86
+ this.#prettyStream.enabled = str === 'pretty-print'
87
+ }
88
+ }
89
+
90
+ get format() {
91
+ return this.#format
92
+ }
93
+
94
+ get fatal() {
95
+ return this.#logger.fatal.bind(this.#logger)
96
+ }
97
+
98
+ get error() {
99
+ return this.#logger.error.bind(this.#logger)
100
+ }
101
+
102
+ get warn() {
103
+ return this.#logger.warn.bind(this.#logger)
104
+ }
105
+
106
+ get info() {
107
+ return this.#logger.info.bind(this.#logger)
108
+ }
109
+
110
+ get debug() {
111
+ return this.#logger.debug.bind(this.#logger)
112
+ }
113
+
114
+ get trace() {
115
+ return this.#logger.trace.bind(this.#logger)
116
+ }
117
+
118
+ get hapiPlugin() {
119
+ return {
120
+ plugin: hapiPino,
121
+ options: {
122
+ instance: this.#logger,
123
+ ignoreFunc: defaultIgnorePath
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ export const logger = new Logger()
@@ -0,0 +1,232 @@
1
+ import { describe, expect, test, vi } from 'vitest'
2
+
3
+ import { logger } from './index.js'
4
+
5
+ describe('Logger', () => {
6
+ describe('serviceName', () => {
7
+ test('it defaults to process.env.SERVICE_NAME', () => {
8
+ // Arrange
9
+ const freshLogging = new logger.constructor()
10
+
11
+ // Act
12
+ // Assert
13
+ expect(freshLogging.serviceName).toBe(process.env.SERVICE_NAME)
14
+ })
15
+
16
+ test('it is settable and surfaces on log lines', () => {
17
+ // Arrange
18
+ const freshLogging = new logger.constructor()
19
+ const writeSpy = vi
20
+ .spyOn(process.stdout, 'write')
21
+ .mockImplementation(() => true)
22
+
23
+ // Act
24
+ freshLogging.serviceName = 'Home for Cattle'
25
+ freshLogging.info('test message')
26
+ const [logLine] = writeSpy.mock.calls[0]
27
+ writeSpy.mockRestore()
28
+
29
+ // Assert
30
+ expect(JSON.parse(logLine.toString()).service.name).toBe(
31
+ 'Home for Cattle'
32
+ )
33
+ })
34
+ })
35
+
36
+ describe('serviceVersion', () => {
37
+ test('it defaults to process.env.SERVICE_VERSION', () => {
38
+ // Arrange
39
+ const freshLogging = new logger.constructor()
40
+
41
+ // Act
42
+ // Assert
43
+ expect(freshLogging.serviceVersion).toBe(process.env.SERVICE_VERSION)
44
+ })
45
+
46
+ test('it is settable and surfaces on log lines', () => {
47
+ // Arrange
48
+ const freshLogging = new logger.constructor()
49
+ const writeSpy = vi
50
+ .spyOn(process.stdout, 'write')
51
+ .mockImplementation(() => true)
52
+
53
+ // Act
54
+ freshLogging.serviceVersion = '1.2.3'
55
+ freshLogging.info('test message')
56
+ const [logLine] = writeSpy.mock.calls[0]
57
+ writeSpy.mockRestore()
58
+
59
+ // Assert
60
+ expect(JSON.parse(logLine.toString()).service.version).toBe('1.2.3')
61
+ })
62
+ })
63
+
64
+ describe('redact', () => {
65
+ test('it removes authorization, cookie and res.headers from logged output', () => {
66
+ // Arrange
67
+ const freshLogging = new logger.constructor()
68
+ const writeSpy = vi
69
+ .spyOn(process.stdout, 'write')
70
+ .mockImplementation(() => true)
71
+
72
+ // Act
73
+ freshLogging.info({
74
+ req: {
75
+ headers: {
76
+ authorization: 'Bearer secret-token',
77
+ cookie: 'session=secret-session'
78
+ }
79
+ },
80
+ res: { headers: { 'set-cookie': 'session=secret-session' } }
81
+ })
82
+ const [logLine] = writeSpy.mock.calls[0]
83
+ writeSpy.mockRestore()
84
+
85
+ // Assert
86
+ expect(logLine.toString()).not.toContain('secret-token')
87
+ expect(logLine.toString()).not.toContain('secret-session')
88
+ })
89
+ })
90
+ describe.each(['fatal', 'error', 'warn', 'info', 'debug', 'trace'])(
91
+ '%s',
92
+ (level) => {
93
+ test('it is callable without configure() being called first', () => {
94
+ // Arrange
95
+ const freshLogging = new logger.constructor()
96
+
97
+ // Act
98
+ // Assert
99
+ expect(typeof freshLogging[level]).toBe('function')
100
+ expect(() => freshLogging[level]('test message')).not.toThrow()
101
+ })
102
+ }
103
+ )
104
+
105
+ describe('hapiPlugin', () => {
106
+ test('it wraps the currently active logger for request logging', () => {
107
+ // Arrange
108
+ const freshLogging = new logger.constructor()
109
+
110
+ // Act
111
+ const plugin = freshLogging.hapiPlugin
112
+
113
+ // Assert
114
+ expect(typeof plugin.options.instance.info).toBe('function')
115
+ })
116
+
117
+ test('it ignores health, public and favicon paths by default', () => {
118
+ // Arrange
119
+ const freshLogging = new logger.constructor()
120
+
121
+ // Act
122
+ const plugin = freshLogging.hapiPlugin
123
+
124
+ // Assert
125
+ expect(plugin.options.ignoreFunc(null, { path: '/health' })).toBe(true)
126
+ expect(plugin.options.ignoreFunc(null, { path: '/profile' })).toBe(false)
127
+ })
128
+ })
129
+
130
+ describe('level', () => {
131
+ test('it defaults to info', () => {
132
+ // Arrange
133
+ const freshLogging = new logger.constructor()
134
+
135
+ // Act
136
+ // Assert
137
+ expect(freshLogging.level).toBe('info')
138
+ })
139
+
140
+ test('it sets the level on the active logger', () => {
141
+ // Arrange
142
+ const freshLogging = new logger.constructor()
143
+
144
+ // Act
145
+ freshLogging.level = 'debug'
146
+
147
+ // Assert
148
+ expect(freshLogging.level).toBe('debug')
149
+ expect(freshLogging.hapiPlugin.options.instance.level).toBe('debug')
150
+ })
151
+
152
+ test('it sets the level on every format variant, not just the active one', () => {
153
+ // Arrange
154
+ const freshLogging = new logger.constructor()
155
+
156
+ // Act
157
+ freshLogging.level = 'warn'
158
+ freshLogging.format = 'pretty-print'
159
+
160
+ // Assert
161
+ expect(freshLogging.hapiPlugin.options.instance.level).toBe('warn')
162
+ })
163
+ })
164
+
165
+ describe('enabled', () => {
166
+ test('it defaults to true', () => {
167
+ // Arrange
168
+ const freshLogging = new logger.constructor()
169
+
170
+ // Act
171
+ // Assert
172
+ expect(freshLogging.enabled).toBe(true)
173
+ })
174
+
175
+ test('it silences the logger when set to false', () => {
176
+ // Arrange
177
+ const freshLogging = new logger.constructor()
178
+
179
+ // Act
180
+ freshLogging.enabled = false
181
+
182
+ // Assert
183
+ expect(freshLogging.hapiPlugin.options.instance.level).toBe('silent')
184
+ })
185
+
186
+ test('it restores the configured level when set back to true', () => {
187
+ // Arrange
188
+ const freshLogging = new logger.constructor()
189
+ freshLogging.level = 'debug'
190
+ freshLogging.enabled = false
191
+
192
+ // Act
193
+ freshLogging.enabled = true
194
+
195
+ // Assert
196
+ expect(freshLogging.hapiPlugin.options.instance.level).toBe('debug')
197
+ })
198
+ })
199
+
200
+ describe('format', () => {
201
+ test('it defaults to ecs', () => {
202
+ // Arrange
203
+ const freshLogging = new logger.constructor()
204
+
205
+ // Act
206
+ // Assert
207
+ expect(freshLogging.format).toBe('ecs')
208
+ })
209
+
210
+ test('it switches which logger is active', () => {
211
+ // Arrange
212
+ const freshLogging = new logger.constructor()
213
+
214
+ // Act
215
+ freshLogging.format = 'pretty-print'
216
+
217
+ // Assert
218
+ expect(freshLogging.format).toBe('pretty-print')
219
+ })
220
+
221
+ test('it ignores an unknown format, leaving the current one active', () => {
222
+ // Arrange
223
+ const freshLogging = new logger.constructor()
224
+
225
+ // Act
226
+ freshLogging.format = 'not-a-real-format'
227
+
228
+ // Assert
229
+ expect(freshLogging.format).toBe('ecs')
230
+ })
231
+ })
232
+ })
@@ -0,0 +1,33 @@
1
+ import * as requestContext from '../request-context.js'
2
+
3
+ /**
4
+ * pino mixin() - merges request-scoped context (correlation_id, user_id,
5
+ * origin_service, cph, animal_id) from the current AsyncLocalStorage store
6
+ * into every log line, mapped onto ECS's tenant.id/tenant.message fields.
7
+ * @returns {object}
8
+ */
9
+ export function mixin() {
10
+ const mixinValues = {}
11
+ const correlationId = requestContext.get('correlation_id')
12
+
13
+ if (correlationId) {
14
+ mixinValues.trace = { id: correlationId }
15
+ }
16
+
17
+ const userId = requestContext.get('user_id')
18
+ if (userId) {
19
+ mixinValues.tenant = { id: userId }
20
+ }
21
+
22
+ const tenantMessage = ['origin_service', 'cph', 'animal_id']
23
+ .map((key) => [key, requestContext.get(key)])
24
+ .filter(([, value]) => value)
25
+ .map(([key, value]) => `${key}=${value}`)
26
+ .join(' ')
27
+
28
+ if (tenantMessage) {
29
+ mixinValues.tenant = { ...mixinValues.tenant, message: tenantMessage }
30
+ }
31
+
32
+ return mixinValues
33
+ }
@@ -0,0 +1,108 @@
1
+ import { describe, expect, test, vi } from 'vitest'
2
+
3
+ import * as requestContext from '../request-context.js'
4
+ import { mixin } from './mixin.js'
5
+
6
+ vi.mock('../request-context.js')
7
+
8
+ const mocks = {
9
+ get: vi.mocked(requestContext.get)
10
+ }
11
+
12
+ describe('mixin()', () => {
13
+ test('it returns an empty object when nothing is set in the request context', () => {
14
+ // Arrange
15
+ mocks.get.mockReturnValue(null)
16
+
17
+ // Act
18
+ const result = mixin()
19
+
20
+ // Assert
21
+ expect(result).toEqual({})
22
+ })
23
+
24
+ test('it maps correlation_id onto trace.id', () => {
25
+ // Arrange
26
+ mocks.get.mockImplementation((key) =>
27
+ key === 'correlation_id' ? 'correlation-1' : null
28
+ )
29
+
30
+ // Act
31
+ const result = mixin()
32
+
33
+ // Assert
34
+ expect(result).toEqual({ trace: { id: 'correlation-1' } })
35
+ })
36
+
37
+ test('it maps user_id onto tenant.id', () => {
38
+ // Arrange
39
+ mocks.get.mockImplementation((key) =>
40
+ key === 'user_id' ? 'hashed-user-1' : null
41
+ )
42
+
43
+ // Act
44
+ const result = mixin()
45
+
46
+ // Assert
47
+ expect(result).toEqual({ tenant: { id: 'hashed-user-1' } })
48
+ })
49
+
50
+ test('it packs a single set field of origin_service, cph and animal_id into tenant.message', () => {
51
+ // Arrange
52
+ mocks.get.mockImplementation((key) =>
53
+ key === 'cph' ? '12/345/6789' : null
54
+ )
55
+
56
+ // Act
57
+ const result = mixin()
58
+
59
+ // Assert
60
+ expect(result).toEqual({ tenant: { message: 'cph=12/345/6789' } })
61
+ })
62
+
63
+ test('it packs multiple set fields of origin_service, cph and animal_id into tenant.message, space-separated and in field order', () => {
64
+ // Arrange
65
+ const values = {
66
+ origin_service: 'front-office',
67
+ cph: '12/345/6789',
68
+ animal_id: 'UK123456789012'
69
+ }
70
+ mocks.get.mockImplementation((key) => values[key] ?? null)
71
+
72
+ // Act
73
+ const result = mixin()
74
+
75
+ // Assert
76
+ expect(result).toEqual({
77
+ tenant: {
78
+ message:
79
+ 'origin_service=front-office cph=12/345/6789 animal_id=UK123456789012'
80
+ }
81
+ })
82
+ })
83
+
84
+ test('it combines trace, tenant.id and tenant.message when everything is set in the request context', () => {
85
+ // Arrange
86
+ const values = {
87
+ correlation_id: 'correlation-1',
88
+ user_id: 'hashed-user-1',
89
+ origin_service: 'front-office',
90
+ cph: '12/345/6789',
91
+ animal_id: 'UK123456789012'
92
+ }
93
+ mocks.get.mockImplementation((key) => values[key] ?? null)
94
+
95
+ // Act
96
+ const result = mixin()
97
+
98
+ // Assert
99
+ expect(result).toEqual({
100
+ trace: { id: 'correlation-1' },
101
+ tenant: {
102
+ id: 'hashed-user-1',
103
+ message:
104
+ 'origin_service=front-office cph=12/345/6789 animal_id=UK123456789012'
105
+ }
106
+ })
107
+ })
108
+ })
@@ -0,0 +1,34 @@
1
+ /** @import { DestinationStream } from 'pino' */
2
+ import { createRequire } from 'node:module'
3
+
4
+ const require = createRequire(import.meta.url)
5
+ const pinoPretty = require('pino-pretty')
6
+
7
+ /**
8
+ * A pino destination stream that can be toggled at runtime between passing
9
+ * ECS JSON lines through unchanged and rendering them via pino-pretty -
10
+ * avoids needing a second pino instance just to get human-readable output.
11
+ * @implements {DestinationStream}
12
+ */
13
+ export class TogglablePrettyStream {
14
+ #pretty
15
+ enabled = false
16
+
17
+ /**
18
+ * @param {object} options - Passed straight through to pino-pretty.
19
+ */
20
+ constructor(options) {
21
+ this.#pretty = pinoPretty(options)
22
+ }
23
+
24
+ /**
25
+ * @param {string} msg
26
+ */
27
+ write(msg) {
28
+ if (this.enabled) {
29
+ this.#pretty.write(msg)
30
+ } else {
31
+ process.stdout.write(msg)
32
+ }
33
+ }
34
+ }
@@ -1,6 +1,37 @@
1
1
  import h2o2 from '@hapi/h2o2'
2
2
 
3
3
  import { getModulesForHub } from '@defra/lis-hubs-infra-registry'
4
+ import * as requestContext from './request-context.js'
5
+
6
+ const lisContextHeaderNames = [
7
+ 'x-lis-origin-service',
8
+ 'x-lis-cph-number',
9
+ 'x-lis-animal-id',
10
+ 'x-lis-user-id'
11
+ ]
12
+
13
+ /**
14
+ * h2o2's passThrough clones the client's original request headers before
15
+ * merging this object on top (Hoek.merge, which skips null/undefined to
16
+ * preserve empty strings) - so every x-lis-* header must be set explicitly,
17
+ * blanking any without a trusted value, or an attacker-supplied header on
18
+ * the original request would pass through to the spoke untouched.
19
+ * @param {string} hubId
20
+ * @returns {object}
21
+ */
22
+ function buildLisContextHeaders(hubId) {
23
+ const headers = Object.fromEntries(
24
+ lisContextHeaderNames.map((header) => [header, ''])
25
+ )
26
+
27
+ Object.assign(headers, requestContext.getHeaders())
28
+
29
+ if (!headers['x-lis-origin-service']) {
30
+ headers['x-lis-origin-service'] = hubId
31
+ }
32
+
33
+ return headers
34
+ }
4
35
 
5
36
  /**
6
37
  * @param {{ hubId: string, environment: string }} options
@@ -63,7 +94,8 @@ export function createProxyPlugin({ hubId, environment }) {
63
94
  'x-forwarded-prefix': path,
64
95
  ...(request.headers.cookie && {
65
96
  cookie: request.headers.cookie
66
- })
97
+ }),
98
+ ...buildLisContextHeaders(hubId)
67
99
  }
68
100
  }
69
101
  }
@@ -2,16 +2,20 @@ import { beforeEach, describe, expect, test, vi } from 'vitest'
2
2
 
3
3
  import { getModulesForHub } from '@defra/lis-hubs-infra-registry'
4
4
  import { createProxyPlugin } from './proxy-plugin.js'
5
+ import { getHeaders } from './request-context.js'
5
6
 
6
7
  vi.mock('@defra/lis-hubs-infra-registry')
8
+ vi.mock('./request-context.js')
7
9
 
8
10
  const mocks = {
9
- getModulesForHub: vi.mocked(getModulesForHub)
11
+ getModulesForHub: vi.mocked(getModulesForHub),
12
+ getHeaders: vi.mocked(getHeaders)
10
13
  }
11
14
 
12
15
  describe('createProxyPlugin()', () => {
13
16
  beforeEach(() => {
14
17
  vi.clearAllMocks()
18
+ mocks.getHeaders.mockReturnValue({})
15
19
  mocks.getModulesForHub.mockReturnValue([
16
20
  { id: 'cattle-home', path: '/cattle', port: 3222 }
17
21
  ])
@@ -46,15 +50,114 @@ describe('createProxyPlugin()', () => {
46
50
  uri: `${expectedBaseUri}/summary-data`,
47
51
  headers: {
48
52
  'x-forwarded-prefix': '/cattle',
49
- cookie: 'session=abc'
53
+ cookie: 'session=abc',
54
+ 'x-lis-origin-service': 'back-office',
55
+ 'x-lis-cph-number': '',
56
+ 'x-lis-animal-id': '',
57
+ 'x-lis-user-id': ''
50
58
  }
51
59
  })
52
60
  expect(route.handler.proxy.mapUri({ params: {}, headers: {} })).toEqual({
53
61
  uri: expectedBaseUri,
54
- headers: { 'x-forwarded-prefix': '/cattle' }
62
+ headers: {
63
+ 'x-forwarded-prefix': '/cattle',
64
+ 'x-lis-origin-service': 'back-office',
65
+ 'x-lis-cph-number': '',
66
+ 'x-lis-animal-id': '',
67
+ 'x-lis-user-id': ''
68
+ }
55
69
  })
56
70
  })
57
71
 
72
+ test('mapUri defaults x-lis-origin-service to the hub id when nothing is set in the request context', async () => {
73
+ // Arrange
74
+ const server = { route: vi.fn(), register: vi.fn() }
75
+ const proxy = createProxyPlugin({
76
+ hubId: 'front-office',
77
+ environment: 'local'
78
+ })
79
+ await proxy.plugin.register(server)
80
+ const { mapUri } = server.route.mock.calls[0][0].handler.proxy
81
+
82
+ // Act
83
+ const headers = mapUri({ params: {}, headers: {} }).headers
84
+
85
+ // Assert
86
+ expect(headers['x-lis-origin-service']).toBe('front-office')
87
+ })
88
+
89
+ test('mapUri forwards cph, animal_id, user_id and an explicitly set origin_service from the request context', async () => {
90
+ // Arrange
91
+ const server = { route: vi.fn(), register: vi.fn() }
92
+ const proxy = createProxyPlugin({
93
+ hubId: 'front-office',
94
+ environment: 'local'
95
+ })
96
+ await proxy.plugin.register(server)
97
+ const { mapUri } = server.route.mock.calls[0][0].handler.proxy
98
+ mocks.getHeaders.mockReturnValue({
99
+ 'x-lis-origin-service': 'front-office',
100
+ 'x-lis-cph-number': '12/345/6789',
101
+ 'x-lis-animal-id': 'UK123456789012',
102
+ 'x-lis-user-id': 'hashed-user-1'
103
+ })
104
+
105
+ // Act
106
+ const headers = mapUri({ params: {}, headers: {} }).headers
107
+
108
+ // Assert
109
+ expect(headers).toMatchObject({
110
+ 'x-lis-origin-service': 'front-office',
111
+ 'x-lis-cph-number': '12/345/6789',
112
+ 'x-lis-animal-id': 'UK123456789012',
113
+ 'x-lis-user-id': 'hashed-user-1'
114
+ })
115
+ })
116
+
117
+ test('mapUri blanks cph, animal_id and user_id when they are not set in the request context', async () => {
118
+ // Arrange
119
+ const server = { route: vi.fn(), register: vi.fn() }
120
+ const proxy = createProxyPlugin({
121
+ hubId: 'front-office',
122
+ environment: 'local'
123
+ })
124
+ await proxy.plugin.register(server)
125
+ const { mapUri } = server.route.mock.calls[0][0].handler.proxy
126
+
127
+ // Act
128
+ const headers = mapUri({ params: {}, headers: {} }).headers
129
+
130
+ // Assert
131
+ expect(headers['x-lis-cph-number']).toBe('')
132
+ expect(headers['x-lis-animal-id']).toBe('')
133
+ expect(headers['x-lis-user-id']).toBe('')
134
+ })
135
+
136
+ test('mapUri always returns every x-lis-* header explicitly, so a client-supplied header on the original request cannot survive h2o2 passThrough merge untouched', async () => {
137
+ // Arrange
138
+ const server = { route: vi.fn(), register: vi.fn() }
139
+ const proxy = createProxyPlugin({
140
+ hubId: 'front-office',
141
+ environment: 'local'
142
+ })
143
+ await proxy.plugin.register(server)
144
+ const { mapUri } = server.route.mock.calls[0][0].handler.proxy
145
+
146
+ // Act
147
+ const { headers } = mapUri({ params: {}, headers: {} })
148
+
149
+ // Assert
150
+ expect(Object.keys(headers).sort()).toEqual(
151
+ [
152
+ 'x-forwarded-prefix',
153
+ 'x-lis-animal-id',
154
+ 'x-lis-cph-number',
155
+ 'x-lis-origin-service',
156
+ 'x-lis-user-id'
157
+ ].sort()
158
+ )
159
+ })
160
+
58
161
  test('rejects an unsupported environment', async () => {
59
162
  // Arrange
60
163
  const server = { route: vi.fn(), register: vi.fn() }
@@ -0,0 +1,20 @@
1
+ import { createHmac } from 'node:crypto'
2
+
3
+ /**
4
+ * Derives a pseudonymous, stable user identifier from an email address,
5
+ * for use as index context - never the raw email itself so that PII leakage is limited.
6
+ * Returns null when either input is missing, so callers can skip setting
7
+ * it rather than deriving a meaningless hash.
8
+ *
9
+ * @param {string} email
10
+ * @param {string} secret - Fixed, securely-stored key. Must not be a
11
+ * per-request or randomly generated value - the same email must always
12
+ * produce the same id, so it can be used to correlate a user's requests.
13
+ * @returns {string | null}
14
+ */
15
+ export function derivePseudonymousUserId(email, secret) {
16
+ if (!email || !secret) {
17
+ return null
18
+ }
19
+ return createHmac('sha256', secret).update(email).digest('hex')
20
+ }
@@ -0,0 +1,60 @@
1
+ import { describe, expect, test } from 'vitest'
2
+
3
+ import { derivePseudonymousUserId } from './pseudonymous-user-id.js'
4
+
5
+ describe('derivePseudonymousUserId()', () => {
6
+ test('it returns the same id for the same email and secret', () => {
7
+ // Arrange
8
+ const email = 'keeper@example.com'
9
+ const secret = 'test-user-id-secret'
10
+
11
+ // Act
12
+ const first = derivePseudonymousUserId(email, secret)
13
+ const second = derivePseudonymousUserId(email, secret)
14
+
15
+ // Assert
16
+ expect(first).toBe(second)
17
+ })
18
+
19
+ test('it returns different ids for different emails', () => {
20
+ // Arrange
21
+ const secret = 'test-user-id-secret'
22
+
23
+ // Act
24
+ const first = derivePseudonymousUserId('keeper-1@example.com', secret)
25
+ const second = derivePseudonymousUserId('keeper-2@example.com', secret)
26
+
27
+ // Assert
28
+ expect(first).not.toBe(second)
29
+ })
30
+
31
+ test('it returns different ids for the same email with different secrets', () => {
32
+ // Arrange
33
+ const email = 'keeper@example.com'
34
+
35
+ // Act
36
+ const first = derivePseudonymousUserId(email, 'secret-one')
37
+ const second = derivePseudonymousUserId(email, 'secret-two')
38
+
39
+ // Assert
40
+ expect(first).not.toBe(second)
41
+ })
42
+
43
+ test('it returns null when the email is missing', () => {
44
+ // Arrange
45
+ // Act
46
+ const result = derivePseudonymousUserId(undefined, 'test-user-id-secret')
47
+
48
+ // Assert
49
+ expect(result).toBeNull()
50
+ })
51
+
52
+ test('it returns null when the secret is missing', () => {
53
+ // Arrange
54
+ // Act
55
+ const result = derivePseudonymousUserId('keeper@example.com', undefined)
56
+
57
+ // Assert
58
+ expect(result).toBeNull()
59
+ })
60
+ })
@@ -2,21 +2,72 @@ import { AsyncLocalStorage } from 'node:async_hooks'
2
2
 
3
3
  const storage = new AsyncLocalStorage()
4
4
 
5
+ const lisHeaderKeys = {
6
+ origin_service: 'x-lis-origin-service',
7
+ cph: 'x-lis-cph-number',
8
+ animal_id: 'x-lis-animal-id',
9
+ user_id: 'x-lis-user-id'
10
+ }
11
+
12
+ const headerKeys = { ...lisHeaderKeys, correlation_id: 'x-cdp-request-id' }
13
+
14
+ /**
15
+ * Maps whichever x-lis-* (and correlation) headers are present on an
16
+ * inbound request onto their corresponding request context keys. The
17
+ * x-lis-* headers are only ever trusted from an internal caller (a spoke
18
+ * receiving them from a hub's own proxy) - anyone can set an arbitrary
19
+ * header on a request, so a hub (the public-facing entry point) must
20
+ * never trust them from its own inbound requests, or a client could
21
+ * inject a fake user_id/cph/origin_service into its logs.
22
+ * @param {object} headers
23
+ * @param {boolean} trustLisHeaders
24
+ * @returns {object}
25
+ */
26
+ const parseHeaders = (headers, trustLisHeaders) => {
27
+ const context = {}
28
+ const keysToParse = trustLisHeaders
29
+ ? headerKeys
30
+ : { correlation_id: headerKeys.correlation_id }
31
+
32
+ for (const [key, header] of Object.entries(keysToParse)) {
33
+ const value = headers[header]
34
+ if (value) {
35
+ context[key] = value
36
+ }
37
+ }
38
+ return context
39
+ }
40
+
5
41
  export const plugin = {
6
42
  name: 'requestContext',
7
43
  version: '1.0.0',
8
- register(server) {
44
+ register(server, options = {}) {
45
+ const { trustLisHeaders = false } = options
46
+
9
47
  server.ext('onRequest', (request, h) => {
10
48
  const store = new Map()
49
+ const context = parseHeaders(request.headers, trustLisHeaders)
11
50
 
12
- store.set(
13
- 'correlation_id',
14
- request.headers['x-cdp-request-id'] || crypto.randomUUID()
15
- )
51
+ if (!context.correlation_id) {
52
+ context.correlation_id = crypto.randomUUID()
53
+ }
54
+
55
+ for (const [key, value] of Object.entries(context)) {
56
+ store.set(key, value)
57
+ }
16
58
 
17
- for (const cycle of ['_lifecycle', '_postCycle']) {
59
+ // _lifecycle covers routing through the handler; _reply covers
60
+ // everything after (including _postCycle, _abort and _finalize,
61
+ // which _reply calls internally) - notably _finalize is where Hapi
62
+ // emits the 'response' event that hapi-pino's request-summary log
63
+ // line listens to. Wrapping _postCycle alone left _finalize running
64
+ // after the storage.run() call for _postCycle had already returned,
65
+ // so context set during the request (e.g. via onPreAuth) never
66
+ // reached that log line - context does not survive back across an
67
+ // awaited storage.run() call into an unwrapped caller.
68
+ for (const cycle of ['_lifecycle', '_reply']) {
18
69
  const original = request[cycle].bind(request)
19
- request[cycle] = () => storage.run(store, original)
70
+ request[cycle] = (...args) => storage.run(store, original, ...args)
20
71
  }
21
72
  return h.continue
22
73
  })
@@ -71,3 +122,22 @@ export const clear = (key) => {
71
122
  export const clearAll = () => {
72
123
  getStore().clear()
73
124
  }
125
+
126
+ /**
127
+ * Reads the current request context and returns the x-lis-* headers for
128
+ * whichever values are set, for consumers to attach to their own outbound
129
+ * requests to other internal LIS services.
130
+ * @returns {object}
131
+ */
132
+ export function getHeaders() {
133
+ const headers = {}
134
+
135
+ for (const [key, header] of Object.entries(headerKeys)) {
136
+ const value = get(key)
137
+ if (value) {
138
+ headers[header] = value
139
+ }
140
+ }
141
+
142
+ return headers
143
+ }
@@ -1,21 +1,28 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
2
  import { afterEach, describe, expect, test, vi } from 'vitest'
3
3
 
4
- import { clear, clearAll, get, plugin, set } from './request-context.js'
4
+ import {
5
+ clear,
6
+ clearAll,
7
+ get,
8
+ getHeaders,
9
+ plugin,
10
+ set
11
+ } from './request-context.js'
5
12
 
6
13
  const mocks = {
7
14
  run: vi.spyOn(AsyncLocalStorage.prototype, 'run'),
8
15
  getStore: vi.spyOn(AsyncLocalStorage.prototype, 'getStore')
9
16
  }
10
17
 
11
- function getStoreFromRequest(headers) {
18
+ function getStoreFromRequest(headers, options) {
12
19
  const ext = vi.fn()
13
20
  const server = { ext }
14
21
 
15
- plugin.register(server)
22
+ plugin.register(server, options)
16
23
 
17
24
  const handler = ext.mock.calls[0][1]
18
- const request = { headers, _lifecycle: vi.fn(), _postCycle: vi.fn() }
25
+ const request = { headers, _lifecycle: vi.fn(), _reply: vi.fn() }
19
26
 
20
27
  handler(request, { continue: Symbol('continue') })
21
28
  request._lifecycle()
@@ -42,7 +49,7 @@ describe('requestContext', () => {
42
49
  expect(ext).toHaveBeenCalledWith('onRequest', expect.any(Function))
43
50
  })
44
51
 
45
- test('onRequest wraps _lifecycle and _postCycle in an ALS context and continues', () => {
52
+ test('onRequest wraps _lifecycle and _reply in an ALS context and continues', () => {
46
53
  // Arrange
47
54
  const ext = vi.fn()
48
55
  const server = { ext }
@@ -50,11 +57,11 @@ describe('requestContext', () => {
50
57
  const [[, handler]] = ext.mock.calls
51
58
  const h = { continue: Symbol('continue') }
52
59
  const lifecycle = vi.fn()
53
- const postCycle = vi.fn()
60
+ const reply = vi.fn()
54
61
  const request = {
55
62
  headers: {},
56
63
  _lifecycle: lifecycle,
57
- _postCycle: postCycle
64
+ _reply: reply
58
65
  }
59
66
 
60
67
  // Act
@@ -62,9 +69,9 @@ describe('requestContext', () => {
62
69
 
63
70
  // Assert
64
71
  expect(request._lifecycle).not.toBe(lifecycle)
65
- expect(request._postCycle).not.toBe(postCycle)
72
+ expect(request._reply).not.toBe(reply)
66
73
  request._lifecycle()
67
- request._postCycle()
74
+ request._reply()
68
75
  expect(mocks.run).toHaveBeenCalledTimes(2)
69
76
  const [firstStore] = mocks.run.mock.calls[0]
70
77
  const [secondStore] = mocks.run.mock.calls[1]
@@ -73,6 +80,25 @@ describe('requestContext', () => {
73
80
  expect(result).toBe(h.continue)
74
81
  })
75
82
 
83
+ test('onRequest forwards arguments through _reply to the original method', () => {
84
+ // Arrange
85
+ const ext = vi.fn()
86
+ const server = { ext }
87
+ plugin.register(server)
88
+ const [[, handler]] = ext.mock.calls
89
+ const h = { continue: Symbol('continue') }
90
+ const reply = vi.fn()
91
+ const request = { headers: {}, _lifecycle: vi.fn(), _reply: reply }
92
+ const exit = new Error('boom')
93
+
94
+ // Act
95
+ handler(request, h)
96
+ request._reply(exit)
97
+
98
+ // Assert
99
+ expect(reply).toHaveBeenCalledWith(exit)
100
+ })
101
+
76
102
  test('onRequest stores correlation_id from the x-cdp-request-id header', () => {
77
103
  // Arrange
78
104
  // Act
@@ -91,6 +117,94 @@ describe('requestContext', () => {
91
117
  expect(typeof store.get('correlation_id')).toBe('string')
92
118
  expect(store.get('correlation_id').length).toBeGreaterThan(0)
93
119
  })
120
+
121
+ test('onRequest stores origin_service, cph, animal_id and user_id from their x-lis-* headers when trustLisHeaders is true', () => {
122
+ // Arrange
123
+ // Act
124
+ const store = getStoreFromRequest(
125
+ {
126
+ 'x-lis-origin-service': 'front-office',
127
+ 'x-lis-cph-number': '12/345/6789',
128
+ 'x-lis-animal-id': 'UK123456789012',
129
+ 'x-lis-user-id': 'hashed-user-1'
130
+ },
131
+ { trustLisHeaders: true }
132
+ )
133
+
134
+ // Assert
135
+ expect(store.get('origin_service')).toBe('front-office')
136
+ expect(store.get('cph')).toBe('12/345/6789')
137
+ expect(store.get('animal_id')).toBe('UK123456789012')
138
+ expect(store.get('user_id')).toBe('hashed-user-1')
139
+ })
140
+
141
+ test('onRequest does not set origin_service, cph, animal_id or user_id when their headers are missing', () => {
142
+ // Arrange
143
+ // Act
144
+ const store = getStoreFromRequest({}, { trustLisHeaders: true })
145
+
146
+ // Assert
147
+ expect(store.has('origin_service')).toBe(false)
148
+ expect(store.has('cph')).toBe(false)
149
+ expect(store.has('animal_id')).toBe(false)
150
+ expect(store.has('user_id')).toBe(false)
151
+ })
152
+
153
+ test('onRequest only stores the x-lis-* headers that are present when trustLisHeaders is true', () => {
154
+ // Arrange
155
+ // Act
156
+ const store = getStoreFromRequest(
157
+ { 'x-lis-cph-number': '12/345/6789' },
158
+ { trustLisHeaders: true }
159
+ )
160
+
161
+ // Assert
162
+ expect(store.get('cph')).toBe('12/345/6789')
163
+ expect(store.has('origin_service')).toBe(false)
164
+ expect(store.has('animal_id')).toBe(false)
165
+ expect(store.has('user_id')).toBe(false)
166
+ })
167
+
168
+ test('onRequest ignores x-lis-* headers by default, even when present, so a client cannot inject them at a hub', () => {
169
+ // Arrange
170
+ // Act
171
+ const store = getStoreFromRequest({
172
+ 'x-lis-origin-service': 'front-office',
173
+ 'x-lis-cph-number': '12/345/6789',
174
+ 'x-lis-animal-id': 'UK123456789012',
175
+ 'x-lis-user-id': 'hashed-user-1'
176
+ })
177
+
178
+ // Assert
179
+ expect(store.has('origin_service')).toBe(false)
180
+ expect(store.has('cph')).toBe(false)
181
+ expect(store.has('animal_id')).toBe(false)
182
+ expect(store.has('user_id')).toBe(false)
183
+ })
184
+
185
+ test('onRequest ignores x-lis-* headers when trustLisHeaders is explicitly false', () => {
186
+ // Arrange
187
+ // Act
188
+ const store = getStoreFromRequest(
189
+ { 'x-lis-cph-number': '12/345/6789' },
190
+ { trustLisHeaders: false }
191
+ )
192
+
193
+ // Assert
194
+ expect(store.has('cph')).toBe(false)
195
+ })
196
+
197
+ test('onRequest still stores correlation_id when trustLisHeaders is false', () => {
198
+ // Arrange
199
+ // Act
200
+ const store = getStoreFromRequest(
201
+ { 'x-cdp-request-id': 'cdp-1' },
202
+ { trustLisHeaders: false }
203
+ )
204
+
205
+ // Assert
206
+ expect(store.get('correlation_id')).toBe('cdp-1')
207
+ })
94
208
  })
95
209
 
96
210
  describe('get()', () => {
@@ -223,4 +337,50 @@ describe('requestContext', () => {
223
337
  expect(store.size).toBe(0)
224
338
  })
225
339
  })
340
+
341
+ describe('getHeaders()', () => {
342
+ test('it returns the x-lis-* headers for whichever context values are set', () => {
343
+ // Arrange
344
+ const store = new Map([
345
+ ['origin_service', 'front-office'],
346
+ ['cph', '12/345/6789'],
347
+ ['animal_id', 'UK123456789012'],
348
+ ['user_id', 'hashed-user-1']
349
+ ])
350
+ mocks.getStore.mockReturnValue(store)
351
+
352
+ // Act
353
+ const result = getHeaders()
354
+
355
+ // Assert
356
+ expect(result).toEqual({
357
+ 'x-lis-origin-service': 'front-office',
358
+ 'x-lis-cph-number': '12/345/6789',
359
+ 'x-lis-animal-id': 'UK123456789012',
360
+ 'x-lis-user-id': 'hashed-user-1'
361
+ })
362
+ })
363
+
364
+ test('it omits headers for context values that are not set', () => {
365
+ // Arrange
366
+ mocks.getStore.mockReturnValue(new Map([['cph', '12/345/6789']]))
367
+
368
+ // Act
369
+ const result = getHeaders()
370
+
371
+ // Assert
372
+ expect(result).toEqual({ 'x-lis-cph-number': '12/345/6789' })
373
+ })
374
+
375
+ test('it returns an empty object when no context values are set', () => {
376
+ // Arrange
377
+ mocks.getStore.mockReturnValue(new Map())
378
+
379
+ // Act
380
+ const result = getHeaders()
381
+
382
+ // Assert
383
+ expect(result).toEqual({})
384
+ })
385
+ })
226
386
  })