@defra/lis-hubs-infra-access 0.1.0-lreg-25.alpha.1

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 ADDED
@@ -0,0 +1,45 @@
1
+ # Hub Access
2
+
3
+ The single shared security package for hubs and livestock modules.
4
+
5
+ Responsibilities:
6
+
7
+ - OIDC authentication and provider-neutral callback handling
8
+ - authentication flow and user session storage
9
+ - hub and hub-to-module token handling
10
+ - secure cookie and return URL handling
11
+ - profile lookup and normalized external identity data
12
+ - provider-role translation and LIS permission expansion
13
+ - resolve which modules a user may access in a hub
14
+ - resolve capabilities for an allowed module
15
+ - map raw permissions into runtime capabilities
16
+ - enforce least-privilege filtering for hub discovery and navigation
17
+
18
+ Provider-specific configuration and claim mapping remain in each deployable
19
+ hub. Front office uses Defra CI and profile-service roles. Back office uses
20
+ Microsoft Entra ID roles and does not call the profile service. Both role
21
+ sources are translated into LIS roles and permissions by this package.
22
+
23
+ For direct public microsite access, the guard canonicalizes both proxied and
24
+ direct-port requests to the microsite's configured `basePath` and sends that
25
+ relative path to the front-office login route. Relative return URLs prevent an
26
+ untrusted host header from becoming an authentication redirect target.
27
+
28
+ This package should depend on hub facts from `@defra/lis-hubs-infra-registry`, not on deployable hub policy.
29
+
30
+ Current implementation notes:
31
+
32
+ - role definitions live in `src/roles.json` and source mappings live in
33
+ `src/role-mappings.json`
34
+ - permissions are derived from translated LIS roles, not trusted from identity
35
+ providers or profile responses
36
+ - hub and hub-to-app JWTs carry LIS roles and an authorization model version,
37
+ but do not carry expanded permissions or holdings
38
+ - apps rehydrate permissions locally from the versioned role definitions before
39
+ evaluating `hasPermission`, `hasRole`, `demandPermission`, or `demandRole`
40
+ - CPH-scoped role assignments remain scoped when permissions are rehydrated
41
+ - `lis-perm-front-office` and `lis-perm-back-office` gate access to the corresponding hub
42
+ - species permissions such as `lis-perm-cattle-read` apply across that species
43
+ - app permissions such as `lis-perm-cattle-register-admin` apply to a specific species app
44
+ - `status` and `home` resolve from the best permission found anywhere on the species
45
+ - back-office permission management modules can be modeled with a `type` and unlocked by `lis-perm-user-read`, `lis-perm-user-write`, or `lis-perm-user-admin`
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@defra/lis-hubs-infra-access",
3
+ "version": "0.1.0-lreg-25.alpha.1",
4
+ "description": "Shared hub access and capability resolution for the livestock platform.",
5
+ "main": "src/index.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/DEFRA/lis-hubs-infra-access.git"
9
+ },
10
+ "exports": {
11
+ ".": "./src/module-access.js",
12
+ "./auth": "./src/auth.js"
13
+ },
14
+ "files": [
15
+ "src"
16
+ ],
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=24"
20
+ },
21
+ "scripts": {
22
+ "format": "prettier --write \"src/**/*.js\" \"**/*.{js,cjs,md,json}\"",
23
+ "format:check": "prettier --check \"src/**/*.js\" \"**/*.{js,cjs,md,json}\"",
24
+ "lint": "eslint .",
25
+ "lint:fix": "eslint . --fix",
26
+ "test": "vitest run",
27
+ "test:coverage": "vitest run --coverage --coverage.provider=istanbul --coverage.reporter=text --coverage.reporter=lcov --coverage.include=\"src/**/*.js\"",
28
+ "prepare": "if [ \"$npm_command\" = \"install\" ] && [ -z \"$CI\" ] && command -v husky >/dev/null 2>&1; then husky; fi",
29
+ "security-audit": "audit-ci",
30
+ "git:pre-commit-hook": "npm run security-audit && npm run format:check && npm run lint"
31
+ },
32
+ "author": "Defra DDTS",
33
+ "license": "OGL-UK-3.0",
34
+ "dependencies": {
35
+ "@defra/lis-hubs-infra-registry": "^0.1.0",
36
+ "jose": "6.2.8",
37
+ "eslint-plugin-jsdoc": "^63.0.8",
38
+ "eslint-plugin-sonarjs": "^4.1.0",
39
+ "neostandard": "0.13.0",
40
+ "convict": "6.2.5",
41
+ "convict-format-with-validator": "6.2.0"
42
+ },
43
+ "peerDependencies": {
44
+ "eslint": "^9.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@defra/lis-infra-eslint-config": "^0.6.0",
48
+ "@vitest/coverage-istanbul": "^4.1.10",
49
+ "audit-ci": "^7.1.0",
50
+ "eslint": "^9.0.0",
51
+ "husky": "^9.1.7",
52
+ "prettier": "^3.9.6",
53
+ "vitest": "^4.1.10"
54
+ }
55
+ }
@@ -0,0 +1,330 @@
1
+ import crypto from 'node:crypto'
2
+
3
+ import { createRemoteJWKSet, jwtVerify } from 'jose'
4
+
5
+ import {
6
+ clearHubAuthFlow,
7
+ createHubAuthFlow,
8
+ getHubAuthFlow,
9
+ getHubAuthSession,
10
+ setHubAuthFlow
11
+ } from './session.js'
12
+ import { getReturnUrlFromRequest, sanitizeReturnUrl } from './tokens.js'
13
+
14
+ async function fetchJson(url, options = {}) {
15
+ const response = await fetch(url, options)
16
+
17
+ if (!response.ok) {
18
+ throw new Error(`Failed to fetch ${url}: ${response.status}`)
19
+ }
20
+
21
+ return response.json()
22
+ }
23
+
24
+ function createProviderResolver({ getProviderConfig, getPrimaryProviderId }) {
25
+ function resolveProviderId(providerId) {
26
+ const resolvedProviderId = providerId ?? getPrimaryProviderId?.()
27
+
28
+ if (!resolvedProviderId) {
29
+ throw new Error('Authentication provider id is required')
30
+ }
31
+
32
+ return resolvedProviderId
33
+ }
34
+
35
+ return function resolveProviderConfig(providerId) {
36
+ const resolvedProviderId = resolveProviderId(providerId)
37
+ const providerConfig = getProviderConfig(resolvedProviderId)
38
+
39
+ if (!providerConfig?.discoveryUrl) {
40
+ throw new Error(
41
+ `OIDC discovery URL is not configured for provider ${resolvedProviderId}`
42
+ )
43
+ }
44
+
45
+ return { providerId: resolvedProviderId, ...providerConfig }
46
+ }
47
+ }
48
+
49
+ function createMetadataLoader(resolveProviderConfig) {
50
+ const providerMetadata = new Map()
51
+
52
+ return async function getOidcMetadata(providerId) {
53
+ const providerConfig = resolveProviderConfig(providerId)
54
+
55
+ if (!providerMetadata.has(providerConfig.providerId)) {
56
+ providerMetadata.set(
57
+ providerConfig.providerId,
58
+ fetchJson(providerConfig.discoveryUrl)
59
+ )
60
+ }
61
+
62
+ return providerMetadata.get(providerConfig.providerId)
63
+ }
64
+ }
65
+
66
+ function createRedirectUriResolver(resolveProviderConfig, getHubOrigin) {
67
+ return function getRedirectUri(providerId) {
68
+ const providerConfig = resolveProviderConfig(providerId)
69
+ return new URL(providerConfig.redirectPath, getHubOrigin()).toString()
70
+ }
71
+ }
72
+
73
+ function createCodeExchanger({
74
+ resolveProviderConfig,
75
+ getOidcMetadata,
76
+ getRedirectUri
77
+ }) {
78
+ return async function exchangeCodeForTokens(providerId, code, codeVerifier) {
79
+ const providerConfig = resolveProviderConfig(providerId)
80
+ const metadata = await getOidcMetadata(providerConfig.providerId)
81
+ const body = new URLSearchParams({
82
+ grant_type: 'authorization_code',
83
+ code,
84
+ redirect_uri: getRedirectUri(providerConfig.providerId),
85
+ client_id: providerConfig.clientId,
86
+ client_secret: providerConfig.clientSecret,
87
+ code_verifier: codeVerifier
88
+ })
89
+
90
+ if (providerConfig.serviceId) {
91
+ body.set('serviceId', providerConfig.serviceId)
92
+ }
93
+
94
+ return fetchJson(metadata.token_endpoint, {
95
+ method: 'POST',
96
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
97
+ body
98
+ })
99
+ }
100
+ }
101
+
102
+ function addAuthorizationParameters(
103
+ authorizationUrl,
104
+ { providerConfig, redirectUri, authFlow }
105
+ ) {
106
+ const parameters = {
107
+ client_id: providerConfig.clientId,
108
+ response_type: 'code',
109
+ scope: 'openid',
110
+ redirect_uri: redirectUri,
111
+ state: authFlow.state,
112
+ nonce: authFlow.nonce,
113
+ code_challenge: crypto
114
+ .createHash('sha256')
115
+ .update(authFlow.codeVerifier)
116
+ .digest('base64url'),
117
+ code_challenge_method: 'S256'
118
+ }
119
+
120
+ for (const [name, value] of Object.entries(parameters)) {
121
+ authorizationUrl.searchParams.set(name, value)
122
+ }
123
+
124
+ if (providerConfig.serviceId) {
125
+ authorizationUrl.searchParams.set('serviceId', providerConfig.serviceId)
126
+ }
127
+ }
128
+
129
+ function createAuthorizationUrlBuilder({
130
+ resolveProviderConfig,
131
+ getOidcMetadata,
132
+ getRedirectUri
133
+ }) {
134
+ return async function buildAuthorizationUrl(request, providerId) {
135
+ const providerConfig = resolveProviderConfig(providerId)
136
+ const metadata = await getOidcMetadata(providerConfig.providerId)
137
+ const authFlow = {
138
+ ...createHubAuthFlow({ returnUrl: getReturnUrlFromRequest(request) }),
139
+ providerId: providerConfig.providerId
140
+ }
141
+
142
+ setHubAuthFlow(request, authFlow)
143
+
144
+ const authorizationUrl = new URL(metadata.authorization_endpoint)
145
+ addAuthorizationParameters(authorizationUrl, {
146
+ providerConfig,
147
+ redirectUri: getRedirectUri(providerConfig.providerId),
148
+ authFlow
149
+ })
150
+ return authorizationUrl.toString()
151
+ }
152
+ }
153
+
154
+ function resolveAuthorizationFlow(request, getPrimaryProviderId) {
155
+ const authFlow = getHubAuthFlow(request)
156
+ const providerId = authFlow?.providerId ?? getPrimaryProviderId?.()
157
+
158
+ if (
159
+ !authFlow?.state ||
160
+ !authFlow?.nonce ||
161
+ !authFlow?.codeVerifier ||
162
+ !providerId
163
+ ) {
164
+ throw new Error('Authentication flow session was not found')
165
+ }
166
+
167
+ return { authFlow, providerId }
168
+ }
169
+
170
+ function validateAuthorizationResponse(request, authFlow) {
171
+ if (request.query?.state !== authFlow.state) {
172
+ throw new Error('State mismatch')
173
+ }
174
+
175
+ if (!request.query?.code) {
176
+ throw new Error('Authorization code was not returned')
177
+ }
178
+ }
179
+
180
+ function validateTokenResponse(tokens) {
181
+ if (!tokens.id_token) {
182
+ throw new Error('Token response did not include an ID token')
183
+ }
184
+ }
185
+
186
+ function validateIdTokenClaims(payload, authFlow, providerConfig) {
187
+ if (payload.nonce !== authFlow.nonce) {
188
+ throw new Error('Nonce mismatch')
189
+ }
190
+
191
+ if (
192
+ providerConfig.serviceId &&
193
+ payload.serviceId &&
194
+ payload.serviceId !== providerConfig.serviceId
195
+ ) {
196
+ throw new Error('Unexpected serviceId claim')
197
+ }
198
+ }
199
+
200
+ function createIdTokenVerifier() {
201
+ const providerJwks = new Map()
202
+
203
+ return async function verifyIdToken(tokens, providerConfig, metadata) {
204
+ if (!providerJwks.has(providerConfig.providerId)) {
205
+ providerJwks.set(
206
+ providerConfig.providerId,
207
+ createRemoteJWKSet(new URL(metadata.jwks_uri))
208
+ )
209
+ }
210
+
211
+ return jwtVerify(
212
+ tokens.id_token,
213
+ providerJwks.get(providerConfig.providerId),
214
+ { issuer: metadata.issuer, audience: providerConfig.clientId }
215
+ )
216
+ }
217
+ }
218
+
219
+ function createAuthorizationCodeCompleter({
220
+ getPrimaryProviderId,
221
+ resolveProviderConfig,
222
+ getOidcMetadata,
223
+ exchangeCodeForTokens,
224
+ verifyIdToken,
225
+ mapUser
226
+ }) {
227
+ return async function completeAuthorizationCodeGrant(request) {
228
+ const { authFlow, providerId } = resolveAuthorizationFlow(
229
+ request,
230
+ getPrimaryProviderId
231
+ )
232
+ validateAuthorizationResponse(request, authFlow)
233
+
234
+ const providerConfig = resolveProviderConfig(providerId)
235
+ const metadata = await getOidcMetadata(providerConfig.providerId)
236
+ const tokens = await exchangeCodeForTokens(
237
+ providerConfig.providerId,
238
+ request.query.code,
239
+ authFlow.codeVerifier
240
+ )
241
+ validateTokenResponse(tokens)
242
+
243
+ const { payload } = await verifyIdToken(tokens, providerConfig, metadata)
244
+ validateIdTokenClaims(payload, authFlow, providerConfig)
245
+
246
+ const user = mapUser(payload, {
247
+ providerId: providerConfig.providerId,
248
+ providerConfig
249
+ })
250
+ const authSession = {
251
+ ...user,
252
+ idToken: tokens.id_token,
253
+ authenticatedAt: new Date().toISOString()
254
+ }
255
+
256
+ clearHubAuthFlow(request)
257
+
258
+ return {
259
+ user,
260
+ authSession,
261
+ accessToken: tokens.access_token ?? null,
262
+ providerId: providerConfig.providerId,
263
+ returnUrl: sanitizeReturnUrl(authFlow.returnUrl)
264
+ }
265
+ }
266
+ }
267
+
268
+ function createLogoutUrlBuilder({
269
+ getPrimaryProviderId,
270
+ getOidcMetadata,
271
+ getHubOrigin
272
+ }) {
273
+ return async function buildLogoutUrl(request) {
274
+ const authSession = getHubAuthSession(request)
275
+ const providerId = authSession?.authProvider ?? getPrimaryProviderId?.()
276
+ const metadata = await getOidcMetadata(providerId)
277
+ const logoutUrl = new URL(metadata.end_session_endpoint)
278
+
279
+ logoutUrl.searchParams.set('post_logout_redirect_uri', getHubOrigin())
280
+
281
+ if (authSession?.idToken) {
282
+ logoutUrl.searchParams.set('id_token_hint', authSession.idToken)
283
+ }
284
+
285
+ return logoutUrl.toString()
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Creates the OIDC operations used by the hub authentication plugin.
291
+ * @param {object} options OIDC client dependencies.
292
+ * @returns {object} OIDC client operations.
293
+ */
294
+ export function createOidcClient(options) {
295
+ const { getProviderConfig, getPrimaryProviderId, getHubOrigin, mapUser } =
296
+ options
297
+ const resolveProviderConfig = createProviderResolver({
298
+ getProviderConfig,
299
+ getPrimaryProviderId
300
+ })
301
+ const getOidcMetadata = createMetadataLoader(resolveProviderConfig)
302
+ const getRedirectUri = createRedirectUriResolver(
303
+ resolveProviderConfig,
304
+ getHubOrigin
305
+ )
306
+ const sharedDependencies = {
307
+ resolveProviderConfig,
308
+ getOidcMetadata,
309
+ getRedirectUri
310
+ }
311
+ const exchangeCodeForTokens = createCodeExchanger(sharedDependencies)
312
+
313
+ return {
314
+ buildAuthorizationUrl: createAuthorizationUrlBuilder(sharedDependencies),
315
+ buildLogoutUrl: createLogoutUrlBuilder({
316
+ getPrimaryProviderId,
317
+ getOidcMetadata,
318
+ getHubOrigin
319
+ }),
320
+ completeAuthorizationCodeGrant: createAuthorizationCodeCompleter({
321
+ getPrimaryProviderId,
322
+ resolveProviderConfig,
323
+ getOidcMetadata,
324
+ exchangeCodeForTokens,
325
+ verifyIdToken: createIdTokenVerifier(),
326
+ mapUser
327
+ }),
328
+ getOidcMetadata
329
+ }
330
+ }
@@ -0,0 +1,219 @@
1
+ import {
2
+ clearHubAuthSession,
3
+ getHubAuthSession,
4
+ setHubAuthSession
5
+ } from './session.js'
6
+ import {
7
+ getHubJwtCookieOptions,
8
+ getReturnUrlFromRequest,
9
+ issueHubJwt
10
+ } from './tokens.js'
11
+ import { getAuthorizedSpecies } from '../module-access.js'
12
+ import { hydrateAuthorization } from '../authorization.js'
13
+
14
+ const ServiceUnavailable = 503
15
+
16
+ function createLoginController({
17
+ getCookieOptions,
18
+ getHubJwtConfig,
19
+ getHubJwtCookieName,
20
+ providerId,
21
+ buildAuthorizationUrl
22
+ }) {
23
+ return {
24
+ options: {
25
+ auth: false
26
+ },
27
+ async handler(request, h) {
28
+ const authSession = getHubAuthSession(request)
29
+ const returnUrl = getReturnUrlFromRequest(request)
30
+
31
+ if (authSession) {
32
+ const jwt = await issueHubJwt(authSession, getHubJwtConfig())
33
+
34
+ return h
35
+ .redirect(returnUrl)
36
+ .state(getHubJwtCookieName(), jwt, getCookieOptions())
37
+ }
38
+
39
+ const resolvedProviderId =
40
+ typeof providerId === 'function' ? providerId() : providerId
41
+ let authorizationUrl
42
+
43
+ try {
44
+ authorizationUrl = await buildAuthorizationUrl(
45
+ request,
46
+ resolvedProviderId
47
+ )
48
+ } catch (error) {
49
+ request.logger?.error?.(error)
50
+
51
+ return h
52
+ .response(
53
+ 'Authentication is not available. Check the hub OIDC configuration.'
54
+ )
55
+ .code(ServiceUnavailable)
56
+ }
57
+
58
+ return h.redirect(authorizationUrl)
59
+ }
60
+ }
61
+ }
62
+
63
+ function createCallbackController({
64
+ getCookieOptions,
65
+ getHubJwtConfig,
66
+ getHubJwtCookieName,
67
+ completeAuthorizationCodeGrant,
68
+ resolveAuthSession
69
+ }) {
70
+ return {
71
+ options: {
72
+ auth: false
73
+ },
74
+ async handler(request, h) {
75
+ if (request.query?.error) {
76
+ throw new Error(request.query?.error_description ?? request.query.error)
77
+ }
78
+
79
+ const { user, authSession, accessToken, returnUrl } =
80
+ await completeAuthorizationCodeGrant(request)
81
+ const authorization = await resolveAuthSession({
82
+ user,
83
+ authSession,
84
+ accessToken
85
+ })
86
+ const enrichedAuthSession = {
87
+ ...authSession,
88
+ ...authorization
89
+ }
90
+ const jwt = await issueHubJwt(enrichedAuthSession, getHubJwtConfig())
91
+
92
+ setHubAuthSession(request, enrichedAuthSession)
93
+
94
+ return h
95
+ .redirect(returnUrl)
96
+ .state(getHubJwtCookieName(), jwt, getCookieOptions())
97
+ }
98
+ }
99
+ }
100
+
101
+ function createLogoutController({
102
+ getCookieOptions,
103
+ getHubJwtCookieName,
104
+ buildLogoutUrl
105
+ }) {
106
+ return {
107
+ options: {
108
+ auth: false
109
+ },
110
+ async handler(request, h) {
111
+ const logoutUrl = await buildLogoutUrl(request)
112
+
113
+ clearHubAuthSession(request)
114
+
115
+ return h
116
+ .redirect(logoutUrl)
117
+ .unstate(getHubJwtCookieName(), getCookieOptions())
118
+ }
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Creates cookie options for hub JWT authentication.
124
+ *
125
+ * @param {object} options - Cookie configuration options.
126
+ * @param {number} options.ttlSeconds - Time to live in seconds for the cookie.
127
+ * @param {boolean} options.isSecure - Whether the cookie should be secure (HTTPS only).
128
+ * @returns {object} Cookie options compatible with Hapi server state configuration.
129
+ */
130
+ export function createHubCookieOptions({ ttlSeconds, isSecure }) {
131
+ return getHubJwtCookieOptions({
132
+ ttlSeconds,
133
+ isSecure
134
+ })
135
+ }
136
+
137
+ /**
138
+ * Creates a Hapi plugin for hub authentication with OIDC support.
139
+ *
140
+ * @param {object} options - Plugin configuration options.
141
+ * @param {string} [options.pluginName='auth'] - Name of the plugin.
142
+ * @param {Function} options.getHubJwtCookieName - Function that returns the JWT cookie name.
143
+ * @param {Function} options.getCookieOptions - Function that returns cookie options.
144
+ * @param {Function} options.getHubJwtConfig - Function that returns JWT configuration.
145
+ * @param {Function} options.resolveAuthSession - Function to resolve and enrich auth session with authorization data.
146
+ * @param {Function} options.buildAuthorizationUrl - Function to build OIDC authorization URL.
147
+ * @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
148
+ * @param {Function} options.buildLogoutUrl - Function to build logout URL.
149
+ * @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Array of login route configurations.
150
+ * @returns {{plugin: {name: string, register: Function}}} Hapi plugin object with registration function.
151
+ */
152
+ export function createHubAuthPlugin({
153
+ pluginName = 'auth',
154
+ getHubJwtCookieName,
155
+ getCookieOptions,
156
+ getHubJwtConfig,
157
+ resolveAuthSession,
158
+ buildAuthorizationUrl,
159
+ completeAuthorizationCodeGrant,
160
+ buildLogoutUrl,
161
+ loginRoutes
162
+ }) {
163
+ const callbackController = createCallbackController({
164
+ getCookieOptions,
165
+ getHubJwtConfig,
166
+ getHubJwtCookieName,
167
+ completeAuthorizationCodeGrant,
168
+ resolveAuthSession
169
+ })
170
+ const logoutController = createLogoutController({
171
+ getCookieOptions,
172
+ getHubJwtCookieName,
173
+ buildLogoutUrl
174
+ })
175
+
176
+ return {
177
+ plugin: {
178
+ name: pluginName,
179
+ register(server) {
180
+ server.state(getHubJwtCookieName(), getCookieOptions())
181
+ server.ext('onPreAuth', (request, h) => {
182
+ const authSession = getHubAuthSession(request)
183
+ request.app.hubAuth = authSession
184
+ ? hydrateAuthorization(authSession)
185
+ : null
186
+ request.app.authorizedSpecies = getAuthorizedSpecies(
187
+ request.app.hubAuth
188
+ )
189
+
190
+ return h.continue
191
+ })
192
+
193
+ server.route([
194
+ ...loginRoutes.map(({ path, providerId }) => ({
195
+ method: 'GET',
196
+ path,
197
+ ...createLoginController({
198
+ getCookieOptions,
199
+ getHubJwtConfig,
200
+ getHubJwtCookieName,
201
+ providerId,
202
+ buildAuthorizationUrl
203
+ })
204
+ })),
205
+ {
206
+ method: 'GET',
207
+ path: '/sso',
208
+ ...callbackController
209
+ },
210
+ {
211
+ method: 'GET',
212
+ path: '/auth/logout',
213
+ ...logoutController
214
+ }
215
+ ])
216
+ }
217
+ }
218
+ }
219
+ }