@defra/lis-hubs-infra-access 0.29.0 → 0.30.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
@@ -116,28 +116,40 @@ await server.register(
116
116
  completeAuthorizationCodeGrant,
117
117
  buildLogoutUrl,
118
118
  loginRoutes,
119
- accessDeniedPath: '/auth/access-denied', // optional
119
+ notAuthorisedPath: '/auth/access-denied', // optional, defaults to '/auth/not-authorised'
120
120
  authorize: async (user, request) => true // optional
121
121
  })
122
122
  )
123
123
  ```
124
124
 
125
125
  Registers the hub JWT cookie state, the login, `/sso`, `/auth/logout` and
126
- `/signout` routes, all with `auth: false`, plus the `lis-hub-session`
126
+ `/signout` routes and the not-authorised route, all with `auth: false`, plus the `lis-hub-session`
127
127
  scheme as the default strategy, backed by the yar hub session. A signed-out
128
128
  user on a required route is redirected to the first login route with
129
129
  `?returnUrl=<path+search>`; a `try` route continues unauthenticated.
130
130
  Credentials are `{ user, authorizedSpecies, caller }`, where `caller` is the
131
131
  hub's own service name (`lis-hubs-<hubId>`), matching the `caller` a spoke
132
132
  sees. `hubId` is required and must be a registry hub id. The optional `authorize`
133
- predicate runs for authenticated requests only; `false` gives a 403.
134
-
135
- `resolveAuthSession` can refuse a login (e.g. a user not on an allow-list) by
136
- returning `{ denied: true }`: the callback then sets no session or JWT and
137
- signs the user out of the identity provider, which returns them to
138
- `accessDeniedPath` (or the hub origin when that isn't set). The hub registers
139
- the `accessDeniedPath` route itself, and the provider must accept it as a
140
- post-logout redirect URI.
133
+ predicate runs for authenticated requests only; `false` refuses the request
134
+ (see below).
135
+
136
+ A hub-level refusal signs the user out and lands them on the not-authorised
137
+ page rather than the login route, which with single sign-on could loop.
138
+ `resolveAuthSession` refuses a login (e.g. a user not on an allow-list) by
139
+ returning `{ denied: true }`, and `authorize` refuses a signed-in user by
140
+ returning `false`. Either way the hub session is cleared, the JWT cookie is
141
+ unset, and the user is signed out of the identity provider, which returns them
142
+ to `notAuthorisedPath`; if the provider has no end-session endpoint, or its
143
+ logout URL cannot be built, they are redirected there directly.
144
+ `notAuthorisedPath` must be a hub path starting with `/`, and the old
145
+ `accessDeniedPath` option is rejected. The provider must accept the path as a post-logout
146
+ redirect URI.
147
+
148
+ By default `notAuthorisedPath` is `/auth/not-authorised`, registered by this
149
+ plugin: it renders the `error/not-authorised` view (from
150
+ `@defra/lis-infra-ui-services`) with a 403, `pageTitle` and a `signInHref` of
151
+ the first login route. A hub that sets its own `notAuthorisedPath` registers
152
+ that route itself. Spoke-level 403s and record-level 404s are not affected.
141
153
 
142
154
  ### Testing routes
143
155
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-access",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Shared hub access and capability resolution for the livestock platform.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -18,6 +18,56 @@ import { hydrateAuthorization } from '../authorization/permissions/hydrate.js'
18
18
  export const HUB_AUTH_STRATEGY = 'lis-hub-session'
19
19
 
20
20
  const ServiceUnavailable = 503
21
+ const Forbidden = 403
22
+
23
+ const DEFAULT_NOT_AUTHORISED_PATH = '/auth/not-authorised'
24
+
25
+ /**
26
+ * Builds the shared response for a hub-level refusal: the user is signed out
27
+ * of the hub and the identity provider and lands on the not-authorised page.
28
+ * With single sign-on, sending them back to login instead could loop.
29
+ *
30
+ * @param {object} options
31
+ * @param {Function} options.buildLogoutUrl - Builds the identity provider's end-session URL.
32
+ * @param {Function} options.getHubJwtCookieName - Returns the hub JWT cookie name.
33
+ * @param {Function} options.getCookieOptions - Returns the hub JWT cookie options.
34
+ * @param {string} options.notAuthorisedPath - Hub path the provider returns the user to.
35
+ * @returns {(request: object, h: object, authSession?: object) => Promise<object>} Clears the session and returns the redirect.
36
+ */
37
+ function createRefuseAccess({
38
+ buildLogoutUrl,
39
+ getHubJwtCookieName,
40
+ getCookieOptions,
41
+ notAuthorisedPath
42
+ }) {
43
+ return async function refuseAccess(
44
+ request,
45
+ h,
46
+ authSession = getHubAuthSession(request)
47
+ ) {
48
+ let logoutUrl
49
+
50
+ // An unavailable identity provider must not leave a refused user signed
51
+ // in, so they are still signed out of the hub and sent to the landing page.
52
+ try {
53
+ logoutUrl = await buildLogoutUrl(request, {
54
+ authSession,
55
+ returnPath: notAuthorisedPath
56
+ })
57
+ } catch (error) {
58
+ logger.warn(
59
+ `Failed to build OIDC logout URL for a refused user [cause=${error?.message}]`
60
+ )
61
+ logoutUrl = notAuthorisedPath
62
+ }
63
+
64
+ clearHubAuthSession(request)
65
+
66
+ return h
67
+ .redirect(logoutUrl)
68
+ .unstate(getHubJwtCookieName(), getCookieOptions())
69
+ }
70
+ }
21
71
 
22
72
  function createLoginController({
23
73
  getCookieOptions,
@@ -77,9 +127,8 @@ function createCallbackController({
77
127
  getHubJwtCookieName,
78
128
  completeAuthorizationCodeGrant,
79
129
  resolveAuthSession,
80
- buildLogoutUrl,
81
- loginPath,
82
- accessDeniedPath
130
+ refuseAccess,
131
+ loginPath
83
132
  }) {
84
133
  return {
85
134
  options: {
@@ -110,17 +159,9 @@ function createCallbackController({
110
159
  // The hub refused this identity (e.g. not on an allow-list): no session
111
160
  // or JWT is issued, any earlier one is dropped, and the user is signed
112
161
  // out of the identity provider so the next login asks for credentials.
162
+ // The refused login was never stored, so its session is passed in.
113
163
  if (authorization?.denied) {
114
- clearHubAuthSession(request)
115
-
116
- const logoutUrl = await buildLogoutUrl(request, {
117
- authSession,
118
- returnPath: accessDeniedPath
119
- })
120
-
121
- return h
122
- .redirect(logoutUrl)
123
- .unstate(getHubJwtCookieName(), getCookieOptions())
164
+ return refuseAccess(request, h, authSession)
124
165
  }
125
166
 
126
167
  const enrichedAuthSession = {
@@ -174,11 +215,33 @@ export function createHubCookieOptions({ ttlSeconds, isSecure }) {
174
215
  })
175
216
  }
176
217
 
218
+ function createNotAuthorisedRoute({ path, loginPath }) {
219
+ return {
220
+ method: 'GET',
221
+ path,
222
+ options: {
223
+ auth: false
224
+ },
225
+ handler(_request, h) {
226
+ // The view comes from @defra/lis-infra-ui-services, which every hub registers.
227
+ return h
228
+ .view('error/not-authorised', {
229
+ pageTitle: 'Sorry, you are not authorised to view this page.',
230
+ signInHref: loginPath
231
+ })
232
+ .code(Forbidden)
233
+ }
234
+ }
235
+ }
236
+
177
237
  /**
178
238
  * Builds the hub JWT cookie state and the login, `/sso`, `/auth/logout` and
179
- * `/signout` routes (all `auth: false`).
239
+ * `/signout` routes (all `auth: false`), plus the shared not-authorised route
240
+ * when the hub uses the default not-authorised path.
180
241
  *
181
242
  * @param {object} options - `createHubAuth` options, minus `pluginName` and `authorize`.
243
+ * @param {Function} options.refuseAccess - Shared hub-level refusal response.
244
+ * @param {boolean} options.registerNotAuthorisedRoute - Whether to register the shared not-authorised route.
182
245
  * @returns {(server: object) => void} Registers the cookie state and routes on a server.
183
246
  */
184
247
  function createHubAuthRegistration(options) {
@@ -191,17 +254,19 @@ function createHubAuthRegistration(options) {
191
254
  completeAuthorizationCodeGrant,
192
255
  buildLogoutUrl,
193
256
  loginRoutes,
194
- accessDeniedPath
257
+ notAuthorisedPath,
258
+ registerNotAuthorisedRoute,
259
+ refuseAccess
195
260
  } = options
261
+ const loginPath = loginRoutes[0].path
196
262
  const callbackController = createCallbackController({
197
263
  getCookieOptions,
198
264
  getHubJwtConfig,
199
265
  getHubJwtCookieName,
200
266
  completeAuthorizationCodeGrant,
201
267
  resolveAuthSession,
202
- buildLogoutUrl,
203
- loginPath: loginRoutes[0].path,
204
- accessDeniedPath
268
+ refuseAccess,
269
+ loginPath
205
270
  })
206
271
  const logoutController = createLogoutController({
207
272
  getCookieOptions,
@@ -241,7 +306,10 @@ function createHubAuthRegistration(options) {
241
306
  handler(_request, h) {
242
307
  return h.redirect('/auth/logout')
243
308
  }
244
- }
309
+ },
310
+ ...(registerNotAuthorisedRoute
311
+ ? [createNotAuthorisedRoute({ path: notAuthorisedPath, loginPath })]
312
+ : [])
245
313
  ]
246
314
 
247
315
  return (server) => {
@@ -284,7 +352,9 @@ function createHubSessionScheme({ loginPath, caller }) {
284
352
  * Creates a Hapi plugin for hub authentication built on a Hapi auth scheme.
285
353
  *
286
354
  * Registers the hub JWT cookie state, the login, `/sso`, `/auth/logout` and
287
- * `/signout` routes (all `auth: false`), and the `lis-hub-session` scheme and
355
+ * `/signout` routes (all `auth: false`), the shared not-authorised route
356
+ * (`auth: false`, unless the hub sets its own `notAuthorisedPath`), and the
357
+ * `lis-hub-session` scheme and
288
358
  * strategy, made the server's default. Signed-out requests to `required`
289
359
  * routes redirect to the first login route with a `returnUrl`; `try` routes
290
360
  * run unauthenticated. Identity is on `request.auth.credentials`
@@ -303,21 +373,53 @@ function createHubSessionScheme({ loginPath, caller }) {
303
373
  * @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
304
374
  * @param {Function} options.buildLogoutUrl - Function to build logout URL.
305
375
  * @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Login route configurations; the first is where signed-out users are sent.
306
- * @param {string} [options.accessDeniedPath] - Where the identity provider returns a user after `resolveAuthSession` refuses them with `{ denied: true }` (they are signed out of the provider first); defaults to the hub origin. The hub registers this route itself.
307
- * @param {(user: object, request: object) => boolean | Promise<boolean>} [options.authorize] - Optional hub-wide rule for authenticated requests; `false` gives a 403.
376
+ * @param {string} [options.notAuthorisedPath='/auth/not-authorised'] - Where a user lands after a hub-level refusal (`resolveAuthSession` returning `{ denied: true }`, or `authorize` returning `false`). They are signed out of the hub and the identity provider first, which returns them here. The default path is registered by this plugin and renders the `error/not-authorised` view with a 403 and a Sign in link to the first login route; a hub that sets its own path registers that route itself.
377
+ * @param {(user: object, request: object) => boolean | Promise<boolean>} [options.authorize] - Optional hub-wide rule for authenticated requests; `false` signs the user out to `notAuthorisedPath`.
308
378
  * @returns {{plugin: {name: string, register: Function}}} Hapi plugin object with registration function.
309
379
  */
310
380
  export function createHubAuth({
311
381
  pluginName = 'auth',
312
382
  hubId,
313
383
  authorize,
384
+ notAuthorisedPath,
314
385
  ...options
315
386
  }) {
316
387
  if (!HUBS.includes(hubId)) {
317
388
  throw new Error(`createHubAuth() requires a hubId of ${HUBS.join(' or ')}`)
318
389
  }
319
390
 
320
- const register = createHubAuthRegistration(options)
391
+ if ('accessDeniedPath' in options) {
392
+ throw new TypeError(
393
+ 'createHubAuth() accessDeniedPath was renamed to notAuthorisedPath'
394
+ )
395
+ }
396
+
397
+ if (
398
+ notAuthorisedPath !== undefined &&
399
+ !(
400
+ typeof notAuthorisedPath === 'string' &&
401
+ notAuthorisedPath.startsWith('/') &&
402
+ !notAuthorisedPath.startsWith('//')
403
+ )
404
+ ) {
405
+ throw new TypeError(
406
+ "createHubAuth() requires notAuthorisedPath to be a hub path starting with '/'"
407
+ )
408
+ }
409
+
410
+ const landingPath = notAuthorisedPath ?? DEFAULT_NOT_AUTHORISED_PATH
411
+ const refuseAccess = createRefuseAccess({
412
+ buildLogoutUrl: options.buildLogoutUrl,
413
+ getHubJwtCookieName: options.getHubJwtCookieName,
414
+ getCookieOptions: options.getCookieOptions,
415
+ notAuthorisedPath: landingPath
416
+ })
417
+ const register = createHubAuthRegistration({
418
+ ...options,
419
+ notAuthorisedPath: landingPath,
420
+ registerNotAuthorisedRoute: notAuthorisedPath === undefined,
421
+ refuseAccess
422
+ })
321
423
  const loginPath = options.loginRoutes[0].path
322
424
  const caller = `lis-hubs-${hubId}`
323
425
 
@@ -340,7 +442,9 @@ export function createHubAuth({
340
442
  request.auth.isAuthenticated &&
341
443
  !(await authorize(request.auth.credentials.user, request))
342
444
  ) {
343
- return Boom.forbidden()
445
+ const response = await refuseAccess(request, h)
446
+
447
+ return response.takeover()
344
448
  }
345
449
 
346
450
  return h.continue
@@ -300,7 +300,7 @@ function createLogoutUrlBuilder({
300
300
  * @param {object} [options]
301
301
  * @param {object} [options.authSession] - Session to sign out instead of the stored hub session (e.g. a refused login that was never stored).
302
302
  * @param {string} [options.returnPath] - Hub path the provider returns to after sign-out; defaults to the hub origin.
303
- * @returns {Promise<string>} The provider's end-session URL.
303
+ * @returns {Promise<string>} The provider's end-session URL, or the return URL itself when the provider has no end-session endpoint.
304
304
  */
305
305
  return async function buildLogoutUrl(
306
306
  request,
@@ -308,11 +308,18 @@ function createLogoutUrlBuilder({
308
308
  ) {
309
309
  const providerId = authSession?.authProvider ?? getPrimaryProviderId?.()
310
310
  const metadata = await getOidcMetadata(providerId)
311
- const logoutUrl = new URL(metadata.end_session_endpoint)
312
311
  const postLogoutRedirectUri = returnPath
313
312
  ? new URL(returnPath, getHubOrigin()).toString()
314
313
  : getHubOrigin()
315
314
 
315
+ // A provider without an end-session endpoint cannot be signed out of, so
316
+ // the user goes straight to where it would have returned them.
317
+ if (!metadata.end_session_endpoint) {
318
+ return postLogoutRedirectUri
319
+ }
320
+
321
+ const logoutUrl = new URL(metadata.end_session_endpoint)
322
+
316
323
  logoutUrl.searchParams.set(
317
324
  'post_logout_redirect_uri',
318
325
  postLogoutRedirectUri