@defra/lis-hubs-infra-access 0.25.0 → 0.26.0-lreg-563.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/README.md +116 -13
- package/package.json +6 -2
- package/src/authentication/{plugin.js → hub-auth.js} +129 -67
- package/src/authentication/index.js +12 -0
- package/src/authentication/logging.js +31 -0
- package/src/authentication/service-token/verifier.js +54 -0
- package/src/authentication/spoke-auth.js +192 -0
- package/src/authentication/tokens/index.js +0 -3
- package/src/authentication/tokens/jwt.js +19 -2
- package/src/authentication/tokens/urls.js +2 -18
- package/src/authorization/index.js +4 -5
- package/src/{module-access/module-access-resolution.js → authorization/modules/module-access.js} +52 -1
- package/src/{module-access → authorization/modules}/species.js +3 -3
- package/src/authorization/{checks.js → permissions/checks.js} +3 -3
- package/src/authorization/{guards.js → permissions/guards.js} +3 -2
- package/src/authorization/{hydrate.js → permissions/hydrate.js} +4 -4
- package/src/{module-access → authorization/permissions}/permission-parsing.js +1 -1
- package/src/authorization/{normalize.js → roles/normalize.js} +1 -1
- package/src/authorization/{resolve.js → roles/resolve.js} +2 -2
- package/src/authorization/{roles-loader.js → roles/roles-loader.js} +3 -3
- package/src/index.js +2 -0
- package/src/auth.js +0 -24
- package/src/authentication/tokens/guards.js +0 -116
- package/src/module-access/access.js +0 -48
- package/src/module-access/guard.js +0 -42
- /package/src/{constants → authorization/permissions}/permissions.js +0 -0
- /package/src/{module-access → authorization/permissions}/statements.js +0 -0
- /package/src/{constants → authorization/roles}/role-mappings.json +0 -0
- /package/src/{constants → authorization/roles}/roles.json +0 -0
package/README.md
CHANGED
|
@@ -16,26 +16,129 @@ Provider-specific configuration and claim mapping remain in each deployable
|
|
|
16
16
|
hub. Front office uses Defra CI roles. Back office uses Microsoft Entra ID
|
|
17
17
|
roles. Both role sources are translated into LIS roles and permissions by this package.
|
|
18
18
|
|
|
19
|
-
For direct public microsite access, the
|
|
19
|
+
For direct public microsite access, the spoke auth scheme canonicalizes both proxied and
|
|
20
20
|
direct-port requests to the microsite's configured `basePath` and sends that
|
|
21
21
|
relative path to the front-office login route. Relative return URLs prevent an
|
|
22
22
|
untrusted host header from becoming an authentication redirect target.
|
|
23
23
|
|
|
24
|
-
##
|
|
24
|
+
## Hapi auth schemes
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Hubs and spokes authenticate through two Hapi auth schemes, each registered as
|
|
27
|
+
the server's default strategy. Identity is on `request.auth.credentials.user`
|
|
28
|
+
(`request.app` carries no auth state); `@defra/lis-infra-ui-services`' nunjucks
|
|
29
|
+
context and `demandPermission` read it from there. Routes opt out with
|
|
30
|
+
`auth: false` (assets, `/health`) or accept signed-out users with
|
|
31
|
+
`auth: { mode: 'try' }` or `auth: { mode: 'optional' }`. A signed-out
|
|
32
|
+
`try`/`optional` spoke request carries no credentials, so `caller` isn't
|
|
33
|
+
available on those requests.
|
|
27
34
|
|
|
28
|
-
|
|
35
|
+
Entry points:
|
|
29
36
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
37
|
+
| Import | Exports |
|
|
38
|
+
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
39
|
+
| `@defra/lis-hubs-infra-access/authentication` | `createHubAuth`, `HUB_AUTH_STRATEGY`, `createSpokeAuth`, `SPOKE_AUTH_STRATEGY`, `createOidcClient`, `createHubCookieOptions`, `getHubJwtCookieOptions`, `issueHubJwt`, `verifyHubJwt` |
|
|
40
|
+
| `@defra/lis-hubs-infra-access/authorization` | `PERMISSIONS`, `hasPermission`, `demandPermission`, `resolveAuthorization`, `GLOBAL_CPH_SCOPE`, `AUTHORIZATION_VERSION` |
|
|
41
|
+
| `@defra/lis-hubs-infra-access` | both of the above as `authentication` and `authorization` namespaces |
|
|
42
|
+
|
|
43
|
+
Prefer the subpath imports: they give plain named imports and simple mocks
|
|
44
|
+
(`vi.mock('@defra/lis-hubs-infra-access/authorization')`).
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import {
|
|
48
|
+
createSpokeAuth,
|
|
49
|
+
getHubJwtCookieOptions
|
|
50
|
+
} from '@defra/lis-hubs-infra-access/authentication'
|
|
51
|
+
import {
|
|
52
|
+
hasPermission,
|
|
53
|
+
PERMISSIONS
|
|
54
|
+
} from '@defra/lis-hubs-infra-access/authorization'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Spoke: `createSpokeAuth`
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
await server.register(
|
|
61
|
+
createSpokeAuth({
|
|
62
|
+
spokeId: 'cattle-home',
|
|
63
|
+
hubOrigins,
|
|
64
|
+
cookieName,
|
|
65
|
+
cookieOptions,
|
|
66
|
+
port,
|
|
67
|
+
basePath,
|
|
68
|
+
secret,
|
|
69
|
+
audience,
|
|
70
|
+
moduleAccess,
|
|
71
|
+
authorize: async (user, request) => true // optional
|
|
72
|
+
})
|
|
73
|
+
)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Registers the `lis-spoke` scheme as the default strategy. A request:
|
|
77
|
+
|
|
78
|
+
1. must carry a valid service token in `Authorization: Bearer <token>`, else
|
|
79
|
+
`401 { message: 'Service authentication required' }` in every route mode,
|
|
80
|
+
`public` spokes included;
|
|
81
|
+
2. must carry a valid hub JWT cookie, unless the spoke is `public`. Without one,
|
|
82
|
+
a required route redirects to `<hubOrigin>/auth/login?returnUrl=…`, and a
|
|
83
|
+
`try` route continues unauthenticated;
|
|
84
|
+
3. then gets `credentials: { user, caller }`, where `caller` is the hub's
|
|
85
|
+
service name.
|
|
86
|
+
|
|
87
|
+
Authenticated requests are then checked against `moduleAccess` (non-public
|
|
88
|
+
spokes) and the optional `authorize` predicate; failing either gives a 403.
|
|
89
|
+
The factory throws for an unknown `spokeId` or an invalid `moduleAccess`.
|
|
90
|
+
|
|
91
|
+
The service token is an AWS STS web identity token, attached by the hub's
|
|
92
|
+
proxy in `@defra/lis-hubs-infra-core`. It must:
|
|
93
|
+
|
|
94
|
+
- be an RS256 JWT signed by a key from `CDP_JWT_JWKS_URI`, issued by
|
|
95
|
+
`CDP_JWT_ISSUER`, with an `exp` claim
|
|
96
|
+
- have the audience `lis-apps-<spokeId>`
|
|
97
|
+
- name the caller as `lis-hubs-front-office` or `lis-hubs-back-office` in the
|
|
98
|
+
`https://sts.amazonaws.com/` claim's `principal_tags.ServiceName`
|
|
99
|
+
|
|
100
|
+
`CDP_JWT_ISSUER` and `CDP_JWT_JWKS_URI` must be set when `createSpokeAuth` is
|
|
101
|
+
called; the CDP platform provides them. The JWKS is fetched with the built-in
|
|
102
|
+
`fetch`, which goes via the CDP proxy through the global dispatcher that
|
|
103
|
+
`setupProxy` (`@defra/lis-infra-ui-services`) installs.
|
|
104
|
+
|
|
105
|
+
### Hub: `createHubAuth`
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
await server.register(
|
|
109
|
+
createHubAuth({
|
|
110
|
+
getHubJwtCookieName,
|
|
111
|
+
getCookieOptions,
|
|
112
|
+
getHubJwtConfig,
|
|
113
|
+
resolveAuthSession,
|
|
114
|
+
buildAuthorizationUrl,
|
|
115
|
+
completeAuthorizationCodeGrant,
|
|
116
|
+
buildLogoutUrl,
|
|
117
|
+
loginRoutes,
|
|
118
|
+
authorize: async (user, request) => true // optional
|
|
119
|
+
})
|
|
120
|
+
)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Registers the hub JWT cookie state, the login, `/sso`, `/auth/logout` and
|
|
124
|
+
`/signout` routes, all with `auth: false`, plus the `lis-hub-session`
|
|
125
|
+
scheme as the default strategy, backed by the yar hub session. A signed-out
|
|
126
|
+
user on a required route is redirected to the first login route with
|
|
127
|
+
`?returnUrl=<path+search>`; a `try` route continues unauthenticated.
|
|
128
|
+
Credentials are `{ user, authorizedSpecies }`. The optional `authorize`
|
|
129
|
+
predicate runs for authenticated requests only; `false` gives a 403.
|
|
130
|
+
|
|
131
|
+
### Testing routes
|
|
132
|
+
|
|
133
|
+
Route tests need neither cookies nor service tokens; inject credentials:
|
|
33
134
|
|
|
34
135
|
```js
|
|
35
|
-
server.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
136
|
+
await server.inject({
|
|
137
|
+
url: '/',
|
|
138
|
+
auth: {
|
|
139
|
+
strategy: SPOKE_AUTH_STRATEGY,
|
|
140
|
+
credentials: { user, caller }
|
|
141
|
+
}
|
|
39
142
|
})
|
|
40
143
|
```
|
|
41
144
|
|
|
@@ -43,8 +146,8 @@ This package should depend on hub facts from `@defra/lis-hubs-infra-registry`, n
|
|
|
43
146
|
|
|
44
147
|
Current implementation notes:
|
|
45
148
|
|
|
46
|
-
- role definitions live in `src/roles.json` and source mappings live in
|
|
47
|
-
`src/role-mappings.json`
|
|
149
|
+
- role definitions live in `src/authorization/roles/roles.json` and source mappings live in
|
|
150
|
+
`src/authorization/roles/role-mappings.json`
|
|
48
151
|
- permissions are derived from translated LIS roles, not trusted from identity
|
|
49
152
|
providers
|
|
50
153
|
- hub and hub-to-app JWTs carry LIS roles and an authorization model version,
|
package/package.json
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@defra/lis-hubs-infra-access",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0-lreg-563.alpha.2",
|
|
4
4
|
"description": "Shared hub access and capability resolution for the livestock platform.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/DEFRA/lis-hubs-infra-access.git"
|
|
8
8
|
},
|
|
9
|
+
"main": "./src/index.js",
|
|
9
10
|
"exports": {
|
|
10
|
-
"
|
|
11
|
+
".": "./src/index.js",
|
|
12
|
+
"./authentication": "./src/authentication/index.js",
|
|
13
|
+
"./authorization": "./src/authorization/index.js"
|
|
11
14
|
},
|
|
12
15
|
"files": [
|
|
13
16
|
"src"
|
|
@@ -48,6 +51,7 @@
|
|
|
48
51
|
"@defra/lis-hubs-infra-registry": "^0.5.0",
|
|
49
52
|
"@defra/lis-infra-eslint-config": "^0.6.0",
|
|
50
53
|
"@hapi/boom": "10.0.1",
|
|
54
|
+
"@hapi/hapi": "21.4.10",
|
|
51
55
|
"@vitest/coverage-istanbul": "^4.1.10",
|
|
52
56
|
"audit-ci": "^7.1.0",
|
|
53
57
|
"eslint": "^9.0.0",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import Boom from '@hapi/boom'
|
|
1
2
|
import { logger } from '@defra/lis-hubs-infra-core'
|
|
2
3
|
|
|
3
4
|
import {
|
|
@@ -10,8 +11,10 @@ import {
|
|
|
10
11
|
getReturnUrlFromRequest,
|
|
11
12
|
issueHubJwt
|
|
12
13
|
} from './tokens/index.js'
|
|
13
|
-
import { getAuthorizedSpecies } from '../
|
|
14
|
-
import { hydrateAuthorization } from '../authorization/
|
|
14
|
+
import { getAuthorizedSpecies } from '../authorization/modules/species.js'
|
|
15
|
+
import { hydrateAuthorization } from '../authorization/permissions/hydrate.js'
|
|
16
|
+
|
|
17
|
+
export const HUB_AUTH_STRATEGY = 'lis-hub-session'
|
|
15
18
|
|
|
16
19
|
const ServiceUnavailable = 503
|
|
17
20
|
|
|
@@ -152,31 +155,23 @@ export function createHubCookieOptions({ ttlSeconds, isSecure }) {
|
|
|
152
155
|
}
|
|
153
156
|
|
|
154
157
|
/**
|
|
155
|
-
*
|
|
158
|
+
* Builds the hub JWT cookie state and the login, `/sso`, `/auth/logout` and
|
|
159
|
+
* `/signout` routes (all `auth: false`).
|
|
156
160
|
*
|
|
157
|
-
* @param {object} options -
|
|
158
|
-
* @
|
|
159
|
-
* @param {Function} options.getHubJwtCookieName - Function that returns the JWT cookie name.
|
|
160
|
-
* @param {Function} options.getCookieOptions - Function that returns cookie options.
|
|
161
|
-
* @param {Function} options.getHubJwtConfig - Function that returns JWT configuration.
|
|
162
|
-
* @param {Function} options.resolveAuthSession - Function to resolve and enrich auth session with authorization data.
|
|
163
|
-
* @param {Function} options.buildAuthorizationUrl - Function to build OIDC authorization URL.
|
|
164
|
-
* @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
|
|
165
|
-
* @param {Function} options.buildLogoutUrl - Function to build logout URL.
|
|
166
|
-
* @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Array of login route configurations.
|
|
167
|
-
* @returns {{plugin: {name: string, register: Function}}} Hapi plugin object with registration function.
|
|
161
|
+
* @param {object} options - `createHubAuth` options, minus `pluginName` and `authorize`.
|
|
162
|
+
* @returns {(server: object) => void} Registers the cookie state and routes on a server.
|
|
168
163
|
*/
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
164
|
+
function createHubAuthRegistration(options) {
|
|
165
|
+
const {
|
|
166
|
+
getHubJwtCookieName,
|
|
167
|
+
getCookieOptions,
|
|
168
|
+
getHubJwtConfig,
|
|
169
|
+
resolveAuthSession,
|
|
170
|
+
buildAuthorizationUrl,
|
|
171
|
+
completeAuthorizationCodeGrant,
|
|
172
|
+
buildLogoutUrl,
|
|
173
|
+
loginRoutes
|
|
174
|
+
} = options
|
|
180
175
|
const callbackController = createCallbackController({
|
|
181
176
|
getCookieOptions,
|
|
182
177
|
getHubJwtConfig,
|
|
@@ -190,56 +185,123 @@ export function createHubAuthPlugin({
|
|
|
190
185
|
getHubJwtCookieName,
|
|
191
186
|
buildLogoutUrl
|
|
192
187
|
})
|
|
188
|
+
const routes = [
|
|
189
|
+
...loginRoutes.map(({ path, providerId }) => ({
|
|
190
|
+
method: 'GET',
|
|
191
|
+
path,
|
|
192
|
+
...createLoginController({
|
|
193
|
+
getCookieOptions,
|
|
194
|
+
getHubJwtConfig,
|
|
195
|
+
getHubJwtCookieName,
|
|
196
|
+
providerId,
|
|
197
|
+
buildAuthorizationUrl
|
|
198
|
+
})
|
|
199
|
+
})),
|
|
200
|
+
{
|
|
201
|
+
method: 'GET',
|
|
202
|
+
path: '/sso',
|
|
203
|
+
...callbackController
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
method: 'GET',
|
|
207
|
+
path: '/auth/logout',
|
|
208
|
+
...logoutController
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
// The shared nunjucks layout's header nav links here (see
|
|
212
|
+
// createNunjucksContextBuilder's logoutUrl default).
|
|
213
|
+
method: 'GET',
|
|
214
|
+
path: '/signout',
|
|
215
|
+
options: {
|
|
216
|
+
auth: false
|
|
217
|
+
},
|
|
218
|
+
handler(_request, h) {
|
|
219
|
+
return h.redirect('/auth/logout')
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
return (server) => {
|
|
225
|
+
server.state(getHubJwtCookieName(), getCookieOptions())
|
|
226
|
+
server.route(routes)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function createHubSessionScheme(loginPath) {
|
|
231
|
+
return () => ({
|
|
232
|
+
authenticate(request, h) {
|
|
233
|
+
const authSession = getHubAuthSession(request)
|
|
234
|
+
|
|
235
|
+
if (authSession) {
|
|
236
|
+
const user = hydrateAuthorization(authSession)
|
|
237
|
+
|
|
238
|
+
return h.authenticated({
|
|
239
|
+
credentials: { user, authorizedSpecies: getAuthorizedSpecies(user) }
|
|
240
|
+
})
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (request.auth.mode === 'required') {
|
|
244
|
+
const returnUrl = encodeURIComponent(
|
|
245
|
+
`${request.path}${request.url.search}`
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
return h.redirect(`${loginPath}?returnUrl=${returnUrl}`).takeover()
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return h.unauthenticated(Boom.unauthorized(null, HUB_AUTH_STRATEGY))
|
|
252
|
+
}
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Creates a Hapi plugin for hub authentication built on a Hapi auth scheme.
|
|
258
|
+
*
|
|
259
|
+
* Registers the hub JWT cookie state, the login, `/sso`, `/auth/logout` and
|
|
260
|
+
* `/signout` routes (all `auth: false`), and the `lis-hub-session` scheme and
|
|
261
|
+
* strategy, made the server's default. Signed-out requests to `required`
|
|
262
|
+
* routes redirect to the first login route with a `returnUrl`; `try` routes
|
|
263
|
+
* run unauthenticated. Identity is on `request.auth.credentials`
|
|
264
|
+
* (`{ user, authorizedSpecies }`).
|
|
265
|
+
*
|
|
266
|
+
* @param {object} options - Plugin configuration options.
|
|
267
|
+
* @param {string} [options.pluginName='auth'] - Name of the plugin.
|
|
268
|
+
* @param {Function} options.getHubJwtCookieName - Function that returns the JWT cookie name.
|
|
269
|
+
* @param {Function} options.getCookieOptions - Function that returns cookie options.
|
|
270
|
+
* @param {Function} options.getHubJwtConfig - Function that returns JWT configuration.
|
|
271
|
+
* @param {Function} options.resolveAuthSession - Function to resolve and enrich auth session with authorization data.
|
|
272
|
+
* @param {Function} options.buildAuthorizationUrl - Function to build OIDC authorization URL.
|
|
273
|
+
* @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
|
|
274
|
+
* @param {Function} options.buildLogoutUrl - Function to build logout URL.
|
|
275
|
+
* @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Login route configurations; the first is where signed-out users are sent.
|
|
276
|
+
* @param {(user: object, request: object) => boolean | Promise<boolean>} [options.authorize] - Optional hub-wide rule for authenticated requests; `false` gives a 403.
|
|
277
|
+
* @returns {{plugin: {name: string, register: Function}}} Hapi plugin object with registration function.
|
|
278
|
+
*/
|
|
279
|
+
export function createHubAuth({ pluginName = 'auth', authorize, ...options }) {
|
|
280
|
+
const register = createHubAuthRegistration(options)
|
|
281
|
+
const loginPath = options.loginRoutes[0].path
|
|
193
282
|
|
|
194
283
|
return {
|
|
195
284
|
plugin: {
|
|
196
285
|
name: pluginName,
|
|
197
286
|
register(server) {
|
|
198
|
-
server.
|
|
199
|
-
server.
|
|
200
|
-
|
|
201
|
-
request.app.hubAuth = authSession
|
|
202
|
-
? hydrateAuthorization(authSession)
|
|
203
|
-
: null
|
|
204
|
-
request.app.authorizedSpecies = getAuthorizedSpecies(
|
|
205
|
-
request.app.hubAuth
|
|
206
|
-
)
|
|
287
|
+
server.auth.scheme(HUB_AUTH_STRATEGY, createHubSessionScheme(loginPath))
|
|
288
|
+
server.auth.strategy(HUB_AUTH_STRATEGY, HUB_AUTH_STRATEGY)
|
|
289
|
+
server.auth.default(HUB_AUTH_STRATEGY)
|
|
207
290
|
|
|
208
|
-
|
|
209
|
-
})
|
|
291
|
+
register(server)
|
|
210
292
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
getHubJwtCookieName,
|
|
219
|
-
providerId,
|
|
220
|
-
buildAuthorizationUrl
|
|
221
|
-
})
|
|
222
|
-
})),
|
|
223
|
-
{
|
|
224
|
-
method: 'GET',
|
|
225
|
-
path: '/sso',
|
|
226
|
-
...callbackController
|
|
227
|
-
},
|
|
228
|
-
{
|
|
229
|
-
method: 'GET',
|
|
230
|
-
path: '/auth/logout',
|
|
231
|
-
...logoutController
|
|
232
|
-
},
|
|
233
|
-
{
|
|
234
|
-
// The shared nunjucks layout's header nav links here (see
|
|
235
|
-
// createNunjucksContextBuilder's logoutUrl default).
|
|
236
|
-
method: 'GET',
|
|
237
|
-
path: '/signout',
|
|
238
|
-
handler(_request, h) {
|
|
239
|
-
return h.redirect('/auth/logout')
|
|
293
|
+
if (authorize) {
|
|
294
|
+
server.ext('onPostAuth', async (request, h) => {
|
|
295
|
+
if (
|
|
296
|
+
request.auth.isAuthenticated &&
|
|
297
|
+
!(await authorize(request.auth.credentials.user, request))
|
|
298
|
+
) {
|
|
299
|
+
return Boom.forbidden()
|
|
240
300
|
}
|
|
241
|
-
|
|
242
|
-
|
|
301
|
+
|
|
302
|
+
return h.continue
|
|
303
|
+
})
|
|
304
|
+
}
|
|
243
305
|
}
|
|
244
306
|
}
|
|
245
307
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createHubAuth,
|
|
3
|
+
createHubCookieOptions,
|
|
4
|
+
HUB_AUTH_STRATEGY
|
|
5
|
+
} from './hub-auth.js'
|
|
6
|
+
export { createOidcClient } from './oidc.js'
|
|
7
|
+
export { createSpokeAuth, SPOKE_AUTH_STRATEGY } from './spoke-auth.js'
|
|
8
|
+
export {
|
|
9
|
+
getHubJwtCookieOptions,
|
|
10
|
+
issueHubJwt,
|
|
11
|
+
verifyHubJwt
|
|
12
|
+
} from './tokens/index.js'
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { logger } from '@defra/lis-hubs-infra-core'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Logs the absence of a usable service token without logging credentials.
|
|
5
|
+
* @param {object} request Hapi request.
|
|
6
|
+
*/
|
|
7
|
+
export function logMissingServiceToken(request) {
|
|
8
|
+
const headerPresent = typeof request.headers?.authorization === 'string'
|
|
9
|
+
|
|
10
|
+
logger.warn(
|
|
11
|
+
`Service token missing or bearer authorization header is malformed [authorizationHeaderPresent=${headerPresent}]`
|
|
12
|
+
)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Logs safe service token validation diagnostics without logging credentials or claims.
|
|
17
|
+
* @param {Error & { code?: string, claim?: string, reason?: string }} error Validation error.
|
|
18
|
+
*/
|
|
19
|
+
export function logInvalidServiceToken(error) {
|
|
20
|
+
const diagnostics = [
|
|
21
|
+
['code', error?.code],
|
|
22
|
+
['claim', error?.claim],
|
|
23
|
+
['reason', error?.reason],
|
|
24
|
+
['message', error?.message]
|
|
25
|
+
]
|
|
26
|
+
.filter(([, value]) => value !== undefined)
|
|
27
|
+
.map(([name, value]) => `${name}=${value}`)
|
|
28
|
+
.join(' | ')
|
|
29
|
+
|
|
30
|
+
logger.warn(`Service token validation failed [${diagnostics}]`)
|
|
31
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createRemoteJWKSet, jwtVerify } from 'jose'
|
|
2
|
+
|
|
3
|
+
const SIGNING_ALGORITHM = 'RS256'
|
|
4
|
+
|
|
5
|
+
function assertNonEmptyString(value, name) {
|
|
6
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
7
|
+
throw new TypeError(`${name} must be a non-empty string`)
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const STS_CLAIM = 'https://sts.amazonaws.com/'
|
|
12
|
+
|
|
13
|
+
// Only the hubs are accepted as callers.
|
|
14
|
+
const ALLOWED_CALLERS = new Set([
|
|
15
|
+
'lis-hubs-front-office',
|
|
16
|
+
'lis-hubs-back-office'
|
|
17
|
+
])
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The issuer and keys come from the platform-provided CDP_JWT_ISSUER and
|
|
21
|
+
* CDP_JWT_JWKS_URI env vars; the audience is the target service's name.
|
|
22
|
+
* Only the two hubs are accepted as callers, by their CDP `ServiceName` tag.
|
|
23
|
+
* @param {{ audience: string }} options
|
|
24
|
+
* @returns {{ verify: (token: string) => Promise<{ serviceName: string }> }}
|
|
25
|
+
*/
|
|
26
|
+
export function createServiceTokenVerifier({ audience }) {
|
|
27
|
+
assertNonEmptyString(audience, 'audience')
|
|
28
|
+
|
|
29
|
+
const issuer = process.env.CDP_JWT_ISSUER
|
|
30
|
+
const jwksUri = process.env.CDP_JWT_JWKS_URI
|
|
31
|
+
if (!issuer?.trim() || !jwksUri?.trim()) {
|
|
32
|
+
throw new Error('CDP_JWT_ISSUER and CDP_JWT_JWKS_URI must be set')
|
|
33
|
+
}
|
|
34
|
+
const jwks = createRemoteJWKSet(new URL(jwksUri))
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
async verify(token) {
|
|
38
|
+
const { payload } = await jwtVerify(token, jwks, {
|
|
39
|
+
issuer,
|
|
40
|
+
audience,
|
|
41
|
+
algorithms: [SIGNING_ALGORITHM],
|
|
42
|
+
requiredClaims: ['exp'],
|
|
43
|
+
maxTokenAge: '15m'
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
const serviceName = payload[STS_CLAIM]?.principal_tags?.ServiceName
|
|
47
|
+
if (!ALLOWED_CALLERS.has(serviceName)) {
|
|
48
|
+
throw new Error(`Service token caller '${serviceName}' is not allowed`)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return { serviceName }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** @import { Module, ModuleAccess } from '../authorization/modules/module-access.js' */
|
|
2
|
+
import Boom from '@hapi/boom'
|
|
3
|
+
|
|
4
|
+
import { hydrateAuthorization } from '../authorization/permissions/hydrate.js'
|
|
5
|
+
import {
|
|
6
|
+
hasModuleAccess,
|
|
7
|
+
normalizeModuleAccess
|
|
8
|
+
} from '../authorization/modules/module-access.js'
|
|
9
|
+
import { logInvalidServiceToken, logMissingServiceToken } from './logging.js'
|
|
10
|
+
import { createServiceTokenVerifier } from './service-token/verifier.js'
|
|
11
|
+
import { getSpokeAccessMode, getSpokeById } from './tokens/access-mode.js'
|
|
12
|
+
import {
|
|
13
|
+
getAuthorizationBearerToken,
|
|
14
|
+
getHubJwtPayloadFromRequest
|
|
15
|
+
} from './tokens/jwt.js'
|
|
16
|
+
import {
|
|
17
|
+
buildHubLoginUrl,
|
|
18
|
+
buildMicrositeReturnUrl,
|
|
19
|
+
resolveHubOrigin
|
|
20
|
+
} from './tokens/urls.js'
|
|
21
|
+
|
|
22
|
+
export const SPOKE_AUTH_STRATEGY = 'lis-spoke'
|
|
23
|
+
|
|
24
|
+
const UNAUTHORIZED = 401
|
|
25
|
+
|
|
26
|
+
function rejectService(h) {
|
|
27
|
+
return h
|
|
28
|
+
.response({ message: 'Service authentication required' })
|
|
29
|
+
.code(UNAUTHORIZED)
|
|
30
|
+
.takeover()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function createCallerVerifier(spokeId) {
|
|
34
|
+
const verifier = createServiceTokenVerifier({
|
|
35
|
+
audience: `lis-apps-${spokeId}`
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
return async (request) => {
|
|
39
|
+
const token = getAuthorizationBearerToken(request)
|
|
40
|
+
|
|
41
|
+
if (!token) {
|
|
42
|
+
logMissingServiceToken(request)
|
|
43
|
+
return null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const { serviceName } = await verifier.verify(token)
|
|
48
|
+
return serviceName
|
|
49
|
+
} catch (error) {
|
|
50
|
+
logInvalidServiceToken(error)
|
|
51
|
+
return null
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function createAuthenticate({
|
|
57
|
+
verifyCaller,
|
|
58
|
+
isPublic,
|
|
59
|
+
hubOrigins,
|
|
60
|
+
cookieName,
|
|
61
|
+
port,
|
|
62
|
+
basePath,
|
|
63
|
+
secret,
|
|
64
|
+
audience
|
|
65
|
+
}) {
|
|
66
|
+
return async (request, h) => {
|
|
67
|
+
const caller = await verifyCaller(request)
|
|
68
|
+
|
|
69
|
+
if (!caller) {
|
|
70
|
+
return rejectService(h)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const payload = await getHubJwtPayloadFromRequest(request, {
|
|
74
|
+
cookieName,
|
|
75
|
+
secret,
|
|
76
|
+
issuer: hubOrigins,
|
|
77
|
+
audience
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
if (!payload && !isPublic) {
|
|
81
|
+
if (request.auth.mode === 'required') {
|
|
82
|
+
const loginUrl = buildHubLoginUrl({
|
|
83
|
+
hubOrigin: resolveHubOrigin(request, hubOrigins),
|
|
84
|
+
returnUrl: buildMicrositeReturnUrl(request, { port, basePath })
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
return h.redirect(loginUrl).takeover()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return h.unauthenticated(Boom.unauthorized(null, SPOKE_AUTH_STRATEGY))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const user = payload ? hydrateAuthorization(payload) : null
|
|
94
|
+
|
|
95
|
+
return h.authenticated({ credentials: { user, caller } })
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function createAccessCheck({ isPublic, moduleAccess, authorize }) {
|
|
100
|
+
return async (request, h) => {
|
|
101
|
+
if (!request.auth.isAuthenticated) {
|
|
102
|
+
return h.continue
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const { user } = request.auth.credentials
|
|
106
|
+
|
|
107
|
+
if (!isPublic && !hasModuleAccess(user, moduleAccess)) {
|
|
108
|
+
return Boom.forbidden()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (authorize && !(await authorize(user, request))) {
|
|
112
|
+
return Boom.forbidden()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return h.continue
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Creates a Hapi plugin that registers the `lis-spoke` auth scheme as the
|
|
121
|
+
* server's default strategy. Every authenticated request needs a valid hub
|
|
122
|
+
* service token (`Authorization: Bearer`) and, unless the spoke is public, a
|
|
123
|
+
* valid hub JWT cookie. Routes opt out with `auth: false`, or accept signed-out
|
|
124
|
+
* users with `auth: { mode: 'try' }` or `auth: { mode: 'optional' }`.
|
|
125
|
+
*
|
|
126
|
+
* @param {object} options
|
|
127
|
+
* @param {string} options.spokeId - Registry id of this spoke; the service token audience is `lis-apps-<spokeId>`.
|
|
128
|
+
* @param {string[]} options.hubOrigins - Accepted hub JWT issuers; the first is the default login origin.
|
|
129
|
+
* @param {string} options.cookieName - Hub JWT cookie name.
|
|
130
|
+
* @param {object} options.cookieOptions - Hapi state options for the hub JWT cookie.
|
|
131
|
+
* @param {number} options.port - Spoke port, used to build the login return URL.
|
|
132
|
+
* @param {string} [options.basePath] - Spoke base path, used to build the login return URL.
|
|
133
|
+
* @param {string} options.secret - Hub JWT signing secret.
|
|
134
|
+
* @param {string} options.audience - Hub JWT audience.
|
|
135
|
+
* @param {ModuleAccess|Module} options.moduleAccess - Module access requirements or module object.
|
|
136
|
+
* @param {(user: object | null, request: object) => boolean | Promise<boolean>} [options.authorize] - Optional spoke-wide rule; `false` gives a 403.
|
|
137
|
+
* @returns {{ plugin: { name: string, register: Function } }}
|
|
138
|
+
*/
|
|
139
|
+
export function createSpokeAuth({
|
|
140
|
+
spokeId,
|
|
141
|
+
hubOrigins,
|
|
142
|
+
cookieName,
|
|
143
|
+
cookieOptions,
|
|
144
|
+
port,
|
|
145
|
+
basePath,
|
|
146
|
+
secret,
|
|
147
|
+
audience,
|
|
148
|
+
moduleAccess,
|
|
149
|
+
authorize
|
|
150
|
+
}) {
|
|
151
|
+
const spoke = getSpokeById(spokeId)
|
|
152
|
+
|
|
153
|
+
if (!spoke) {
|
|
154
|
+
throw new Error(`Unable to resolve spoke configuration for ${spokeId}`)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const resolvedModuleAccess = normalizeModuleAccess(moduleAccess)
|
|
158
|
+
|
|
159
|
+
if (!resolvedModuleAccess) {
|
|
160
|
+
throw new Error('Unable to resolve module access configuration')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const isPublic = getSpokeAccessMode(spoke) === 'public'
|
|
164
|
+
const authenticate = createAuthenticate({
|
|
165
|
+
verifyCaller: createCallerVerifier(spokeId),
|
|
166
|
+
isPublic,
|
|
167
|
+
hubOrigins,
|
|
168
|
+
cookieName,
|
|
169
|
+
port,
|
|
170
|
+
basePath,
|
|
171
|
+
secret,
|
|
172
|
+
audience
|
|
173
|
+
})
|
|
174
|
+
const accessCheck = createAccessCheck({
|
|
175
|
+
isPublic,
|
|
176
|
+
moduleAccess: resolvedModuleAccess,
|
|
177
|
+
authorize
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
plugin: {
|
|
182
|
+
name: 'spokeAuth',
|
|
183
|
+
register(server) {
|
|
184
|
+
server.state(cookieName, cookieOptions)
|
|
185
|
+
server.auth.scheme(SPOKE_AUTH_STRATEGY, () => ({ authenticate }))
|
|
186
|
+
server.auth.strategy(SPOKE_AUTH_STRATEGY, SPOKE_AUTH_STRATEGY)
|
|
187
|
+
server.auth.default(SPOKE_AUTH_STRATEGY)
|
|
188
|
+
server.ext('onPostAuth', accessCheck)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -11,7 +11,6 @@ export {
|
|
|
11
11
|
buildCurrentRequestUrl,
|
|
12
12
|
buildMicrositeReturnUrl,
|
|
13
13
|
buildHubLoginUrl,
|
|
14
|
-
isPublicRequest,
|
|
15
14
|
resolveHubOrigin
|
|
16
15
|
} from './urls.js'
|
|
17
16
|
|
|
@@ -20,5 +19,3 @@ export {
|
|
|
20
19
|
getSpokeById,
|
|
21
20
|
getSpokeAccessMode
|
|
22
21
|
} from './access-mode.js'
|
|
23
|
-
|
|
24
|
-
export { createAuthGuard, createSpokeGuard } from './guards.js'
|
|
@@ -3,7 +3,7 @@ import { TextEncoder } from 'node:util'
|
|
|
3
3
|
|
|
4
4
|
import { SignJWT, jwtVerify } from 'jose'
|
|
5
5
|
|
|
6
|
-
import { AUTHORIZATION_VERSION } from '../../authorization/
|
|
6
|
+
import { AUTHORIZATION_VERSION } from '../../authorization/constants.js'
|
|
7
7
|
|
|
8
8
|
const encoder = new TextEncoder()
|
|
9
9
|
const MILLISECONDS_PER_SECOND = 1000
|
|
@@ -65,7 +65,8 @@ export async function issueHubJwt(
|
|
|
65
65
|
export async function verifyHubJwt(token, { secret, issuer, audience }) {
|
|
66
66
|
const { payload } = await jwtVerify(token, getHubJwtSecret(secret), {
|
|
67
67
|
issuer,
|
|
68
|
-
audience
|
|
68
|
+
audience,
|
|
69
|
+
algorithms: ['HS256']
|
|
69
70
|
})
|
|
70
71
|
|
|
71
72
|
if (payload.authzVersion !== AUTHORIZATION_VERSION) {
|
|
@@ -75,6 +76,22 @@ export async function verifyHubJwt(token, { secret, issuer, audience }) {
|
|
|
75
76
|
return payload
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
/**
|
|
80
|
+
* @param {Request} request
|
|
81
|
+
* @returns {string | null}
|
|
82
|
+
*/
|
|
83
|
+
export function getAuthorizationBearerToken(request) {
|
|
84
|
+
const authorizationHeader = request.headers?.authorization
|
|
85
|
+
|
|
86
|
+
if (typeof authorizationHeader !== 'string') {
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const [scheme, token] = authorizationHeader.split(/\s+/)
|
|
91
|
+
|
|
92
|
+
return scheme?.toLowerCase() === 'bearer' && token ? token : null
|
|
93
|
+
}
|
|
94
|
+
|
|
78
95
|
/**
|
|
79
96
|
* @param {Request} request
|
|
80
97
|
* @param {{ cookieName: string, secret: string, issuer: string, audience: string }} options
|
|
@@ -54,8 +54,8 @@ export function getReturnUrlFromRequest(request) {
|
|
|
54
54
|
* @returns {URL}
|
|
55
55
|
*/
|
|
56
56
|
export function buildCurrentRequestUrl(request, port) {
|
|
57
|
-
const protocol = request.headers['x-forwarded-proto'] ?? 'http'
|
|
58
|
-
const host = request.headers.host ?? `localhost:${port}`
|
|
57
|
+
const protocol = String(request.headers['x-forwarded-proto'] ?? 'http')
|
|
58
|
+
const host = String(request.headers.host ?? `localhost:${port}`)
|
|
59
59
|
const currentUrl = new URL(
|
|
60
60
|
request.raw.req.url ?? request.path,
|
|
61
61
|
`${protocol}://${host}`
|
|
@@ -107,22 +107,6 @@ export function buildHubLoginUrl({ hubOrigin, returnUrl }) {
|
|
|
107
107
|
return loginUrl.toString()
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
/**
|
|
111
|
-
* Assets count as public only at the start of the path - never anywhere
|
|
112
|
-
* in it, or a route such as /holdings/public/x/y would skip authentication.
|
|
113
|
-
* @param {Request} request
|
|
114
|
-
* @param {string} assetPath
|
|
115
|
-
* @returns {boolean}
|
|
116
|
-
*/
|
|
117
|
-
export function isPublicRequest(request, assetPath) {
|
|
118
|
-
return (
|
|
119
|
-
request.path === '/favicon.ico' ||
|
|
120
|
-
request.path === '/health' ||
|
|
121
|
-
request.path === assetPath ||
|
|
122
|
-
request.path.startsWith(`${assetPath}/`)
|
|
123
|
-
)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
110
|
/**
|
|
127
111
|
* @param {Request} request
|
|
128
112
|
* @param {string[]} hubOrigins
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export { AUTHORIZATION_VERSION, GLOBAL_CPH_SCOPE } from './constants.js'
|
|
2
|
-
export { resolveAuthorization } from './resolve.js'
|
|
3
|
-
export {
|
|
4
|
-
export {
|
|
5
|
-
export {
|
|
6
|
-
export { PERMISSIONS } from '../constants/permissions.js'
|
|
2
|
+
export { resolveAuthorization } from './roles/resolve.js'
|
|
3
|
+
export { hasPermission } from './permissions/checks.js'
|
|
4
|
+
export { demandPermission } from './permissions/guards.js'
|
|
5
|
+
export { PERMISSIONS } from './permissions/permissions.js'
|
package/src/{module-access/module-access-resolution.js → authorization/modules/module-access.js}
RENAMED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
/** @import { User } from '../permissions/statements.js' */
|
|
2
|
+
import {
|
|
3
|
+
ACCESS_LEVEL_RANKS,
|
|
4
|
+
parsePermission
|
|
5
|
+
} from '../permissions/permission-parsing.js'
|
|
6
|
+
import { getFlatPermissions } from '../permissions/statements.js'
|
|
7
|
+
|
|
1
8
|
/**
|
|
2
9
|
* @typedef {object} ModuleAccess
|
|
3
10
|
* @property {string} [species] - Species identifier (e.g., 'cattle', 'pigs')
|
|
@@ -56,7 +63,7 @@ function getModuleSpecies(module) {
|
|
|
56
63
|
* @param {Module} module - Module object to resolve access for
|
|
57
64
|
* @returns {ModuleAccess|null} Resolved module access configuration or null if unresolvable
|
|
58
65
|
*/
|
|
59
|
-
|
|
66
|
+
function resolveModuleAccess(module) {
|
|
60
67
|
if (module?.access) {
|
|
61
68
|
return module.access
|
|
62
69
|
}
|
|
@@ -102,3 +109,47 @@ export function normalizeModuleAccess(moduleAccess) {
|
|
|
102
109
|
|
|
103
110
|
return resolveModuleAccess(moduleAccess)
|
|
104
111
|
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Checks whether a user has the required permissions to access a module.
|
|
115
|
+
* Compares user permissions against module scope, species, app, and
|
|
116
|
+
* minimum access level.
|
|
117
|
+
*
|
|
118
|
+
* @param {User} user - Hydrated authorization object
|
|
119
|
+
* @param {ModuleAccess} moduleAccess - Module access requirements
|
|
120
|
+
* @returns {boolean} True if user has sufficient access, false otherwise
|
|
121
|
+
*/
|
|
122
|
+
export function hasModuleAccess(user, moduleAccess) {
|
|
123
|
+
if (!moduleAccess?.minLevel) {
|
|
124
|
+
return false
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const permissions = getFlatPermissions(user)
|
|
128
|
+
const requiredRank = ACCESS_LEVEL_RANKS[moduleAccess.minLevel] ?? 0
|
|
129
|
+
|
|
130
|
+
return permissions.some((permission) => {
|
|
131
|
+
const parsedPermission = parsePermission(permission)
|
|
132
|
+
|
|
133
|
+
if (parsedPermission?.scope !== moduleAccess.scope) {
|
|
134
|
+
return false
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (parsedPermission.levelRank < requiredRank) {
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (moduleAccess.scope === 'user') {
|
|
142
|
+
return true
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (parsedPermission.species !== moduleAccess.species) {
|
|
146
|
+
return false
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (moduleAccess.scope === 'species') {
|
|
150
|
+
return true
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return parsedPermission.app === moduleAccess.app
|
|
154
|
+
})
|
|
155
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/** @import { User } from '
|
|
1
|
+
/** @import { User } from '../permissions/statements.js' */
|
|
2
2
|
import { SPECIES } from '@defra/lis-hubs-infra-registry'
|
|
3
|
-
import { parsePermission } from '
|
|
4
|
-
import { getFlatPermissions } from '
|
|
3
|
+
import { parsePermission } from '../permissions/permission-parsing.js'
|
|
4
|
+
import { getFlatPermissions } from '../permissions/statements.js'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Extracts all species the user has permissions for from their permission set.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** @import { Permission } from '
|
|
2
|
-
/** @import { HydratedAuthorization } from '
|
|
3
|
-
import { GLOBAL_CPH_SCOPE } from '
|
|
1
|
+
/** @import { Permission } from './permissions.js' */
|
|
2
|
+
/** @import { HydratedAuthorization } from '../types.js' */
|
|
3
|
+
import { GLOBAL_CPH_SCOPE } from '../constants.js'
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* @param {'*'|string[]} cphs
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** @import { Permission } from '
|
|
1
|
+
/** @import { Permission } from './permissions.js' */
|
|
2
2
|
import Boom from '@hapi/boom'
|
|
3
3
|
import { hasPermission } from './checks.js'
|
|
4
4
|
|
|
@@ -19,8 +19,9 @@ export function demandPermission({ permission, getCph } = {}) {
|
|
|
19
19
|
|
|
20
20
|
return function permissionDemand(request, h) {
|
|
21
21
|
const cph = getCph?.(request)
|
|
22
|
+
const user = request.auth?.credentials?.user
|
|
22
23
|
|
|
23
|
-
if (hasPermission(
|
|
24
|
+
if (hasPermission(user, { permission, cph })) {
|
|
24
25
|
return h.continue
|
|
25
26
|
}
|
|
26
27
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/** @import { Authorization, HydratedAuthorization } from '
|
|
2
|
-
import { AUTHORIZATION_VERSION } from '
|
|
3
|
-
import { normalizeStatements } from '
|
|
4
|
-
import { resolvedRoleDefinitions } from '
|
|
1
|
+
/** @import { Authorization, HydratedAuthorization } from '../types.js' */
|
|
2
|
+
import { AUTHORIZATION_VERSION } from '../constants.js'
|
|
3
|
+
import { normalizeStatements } from '../roles/normalize.js'
|
|
4
|
+
import { resolvedRoleDefinitions } from '../roles/roles-loader.js'
|
|
5
5
|
import { logger } from '@defra/lis-hubs-infra-core'
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import roleMappings from '
|
|
1
|
+
import roleMappings from './role-mappings.json' with { type: 'json' }
|
|
2
2
|
import {
|
|
3
3
|
AUTHORIZATION_VERSION,
|
|
4
4
|
DEFAULT_ROLE,
|
|
5
5
|
GLOBAL_CPH_SCOPE
|
|
6
|
-
} from '
|
|
6
|
+
} from '../constants.js'
|
|
7
7
|
import { normalizeHoldingRoles } from './normalize.js'
|
|
8
8
|
import { resolvedRoleDefinitions } from './roles-loader.js'
|
|
9
9
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** @import { Permission } from '../
|
|
2
|
-
import roleDefinitions from '
|
|
3
|
-
import { PERMISSIONS } from '../
|
|
1
|
+
/** @import { Permission } from '../permissions/permissions.js' */
|
|
2
|
+
import roleDefinitions from './roles.json' with { type: 'json' }
|
|
3
|
+
import { PERMISSIONS } from '../permissions/permissions.js'
|
|
4
4
|
|
|
5
5
|
const knownPermissions = new Set(Object.values(PERMISSIONS))
|
|
6
6
|
|
package/src/index.js
ADDED
package/src/auth.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
export { createOidcClient } from './authentication/oidc.js'
|
|
2
|
-
|
|
3
|
-
export {
|
|
4
|
-
createHubAuthPlugin,
|
|
5
|
-
createHubCookieOptions
|
|
6
|
-
} from './authentication/plugin.js'
|
|
7
|
-
|
|
8
|
-
export {
|
|
9
|
-
createSpokeGuard,
|
|
10
|
-
getHubJwtCookieOptions,
|
|
11
|
-
issueHubJwt,
|
|
12
|
-
verifyHubJwt
|
|
13
|
-
} from './authentication/tokens/index.js'
|
|
14
|
-
|
|
15
|
-
export {
|
|
16
|
-
AUTHORIZATION_VERSION,
|
|
17
|
-
demandPermission,
|
|
18
|
-
GLOBAL_CPH_SCOPE,
|
|
19
|
-
hasPermission,
|
|
20
|
-
PERMISSIONS,
|
|
21
|
-
resolveAuthorization
|
|
22
|
-
} from './authorization/index.js'
|
|
23
|
-
|
|
24
|
-
export { createModuleAccessGuard } from './module-access/guard.js'
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
/** @import { Request } from '@hapi/hapi' */
|
|
2
|
-
import { hydrateAuthorization } from '../../authorization/index.js'
|
|
3
|
-
import { getSpokeAccessMode, getSpokeById } from './access-mode.js'
|
|
4
|
-
import { getHubJwtPayloadFromRequest } from './jwt.js'
|
|
5
|
-
import {
|
|
6
|
-
buildHubLoginUrl,
|
|
7
|
-
buildMicrositeReturnUrl,
|
|
8
|
-
isPublicRequest,
|
|
9
|
-
resolveHubOrigin
|
|
10
|
-
} from './urls.js'
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* @param {{ name: string, assetPath: string, registerState?: Function, authenticate: Function }} options
|
|
14
|
-
* @returns {object}
|
|
15
|
-
*/
|
|
16
|
-
function createRequestGuard({ name, assetPath, registerState, authenticate }) {
|
|
17
|
-
return {
|
|
18
|
-
plugin: {
|
|
19
|
-
name,
|
|
20
|
-
register(server) {
|
|
21
|
-
registerState?.(server)
|
|
22
|
-
|
|
23
|
-
server.ext('onPreAuth', async (request, h) => {
|
|
24
|
-
if (isPublicRequest(request, assetPath)) {
|
|
25
|
-
return h.continue
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
return authenticate(request, h)
|
|
29
|
-
})
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* @param {{ hubOrigins: string[], cookieName: string, cookieOptions: object, assetPath: string, port: number, secret: string, audience: string }} options
|
|
37
|
-
* @returns {object}
|
|
38
|
-
*/
|
|
39
|
-
export function createAuthGuard({
|
|
40
|
-
hubOrigins,
|
|
41
|
-
cookieName,
|
|
42
|
-
cookieOptions,
|
|
43
|
-
assetPath,
|
|
44
|
-
port,
|
|
45
|
-
basePath,
|
|
46
|
-
secret,
|
|
47
|
-
audience
|
|
48
|
-
}) {
|
|
49
|
-
return createRequestGuard({
|
|
50
|
-
name: 'authGuard',
|
|
51
|
-
assetPath,
|
|
52
|
-
registerState(server) {
|
|
53
|
-
server.state(cookieName, cookieOptions)
|
|
54
|
-
},
|
|
55
|
-
async authenticate(request, h) {
|
|
56
|
-
const hubJwtPayload = await getHubJwtPayloadFromRequest(request, {
|
|
57
|
-
cookieName,
|
|
58
|
-
secret,
|
|
59
|
-
issuer: hubOrigins,
|
|
60
|
-
audience
|
|
61
|
-
})
|
|
62
|
-
|
|
63
|
-
if (!hubJwtPayload) {
|
|
64
|
-
const loginUrl = buildHubLoginUrl({
|
|
65
|
-
hubOrigin: resolveHubOrigin(request, hubOrigins),
|
|
66
|
-
returnUrl: buildMicrositeReturnUrl(request, { port, basePath })
|
|
67
|
-
})
|
|
68
|
-
|
|
69
|
-
return h.redirect(loginUrl).takeover()
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
request.app.hubAuth = hydrateAuthorization(hubJwtPayload)
|
|
73
|
-
request.app.hubOrigin = resolveHubOrigin(request, hubOrigins)
|
|
74
|
-
return h.continue
|
|
75
|
-
}
|
|
76
|
-
})
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* @param {{ spokeId: string, hubOrigins: string[], cookieName: string, cookieOptions: object, assetPath: string, port: number, secret: string, audience: string }} options
|
|
81
|
-
* @returns {object | null}
|
|
82
|
-
*/
|
|
83
|
-
export function createSpokeGuard({
|
|
84
|
-
spokeId,
|
|
85
|
-
hubOrigins,
|
|
86
|
-
cookieName,
|
|
87
|
-
cookieOptions,
|
|
88
|
-
assetPath,
|
|
89
|
-
port,
|
|
90
|
-
basePath,
|
|
91
|
-
secret,
|
|
92
|
-
audience
|
|
93
|
-
}) {
|
|
94
|
-
const spoke = getSpokeById(spokeId)
|
|
95
|
-
|
|
96
|
-
if (!spoke) {
|
|
97
|
-
throw new Error(`Unable to resolve spoke configuration for ${spokeId}`)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const accessMode = getSpokeAccessMode(spoke)
|
|
101
|
-
|
|
102
|
-
if (accessMode === 'public') {
|
|
103
|
-
return null
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return createAuthGuard({
|
|
107
|
-
hubOrigins,
|
|
108
|
-
cookieName,
|
|
109
|
-
cookieOptions,
|
|
110
|
-
assetPath,
|
|
111
|
-
port,
|
|
112
|
-
basePath,
|
|
113
|
-
secret,
|
|
114
|
-
audience
|
|
115
|
-
})
|
|
116
|
-
}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/** @import { ModuleAccess } from './module-access-resolution.js' */
|
|
2
|
-
/** @import { User } from './statements.js' */
|
|
3
|
-
import { ACCESS_LEVEL_RANKS, parsePermission } from './permission-parsing.js'
|
|
4
|
-
import { getFlatPermissions } from './statements.js'
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Checks whether a user has the required permissions to access a module.
|
|
8
|
-
* Compares user permissions against module scope, species, app, and
|
|
9
|
-
* minimum access level.
|
|
10
|
-
*
|
|
11
|
-
* @param {User} user - Hydrated authorization object
|
|
12
|
-
* @param {ModuleAccess} moduleAccess - Module access requirements
|
|
13
|
-
* @returns {boolean} True if user has sufficient access, false otherwise
|
|
14
|
-
*/
|
|
15
|
-
export function hasModuleAccess(user, moduleAccess) {
|
|
16
|
-
if (!moduleAccess?.minLevel) {
|
|
17
|
-
return false
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const permissions = getFlatPermissions(user)
|
|
21
|
-
const requiredRank = ACCESS_LEVEL_RANKS[moduleAccess.minLevel] ?? 0
|
|
22
|
-
|
|
23
|
-
return permissions.some((permission) => {
|
|
24
|
-
const parsedPermission = parsePermission(permission)
|
|
25
|
-
|
|
26
|
-
if (parsedPermission?.scope !== moduleAccess.scope) {
|
|
27
|
-
return false
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
if (parsedPermission.levelRank < requiredRank) {
|
|
31
|
-
return false
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (moduleAccess.scope === 'user') {
|
|
35
|
-
return true
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
if (parsedPermission.species !== moduleAccess.species) {
|
|
39
|
-
return false
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (moduleAccess.scope === 'species') {
|
|
43
|
-
return true
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
return parsedPermission.app === moduleAccess.app
|
|
47
|
-
})
|
|
48
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/** @import { Module, ModuleAccess } from './module-access-resolution.js' */
|
|
2
|
-
import Boom from '@hapi/boom'
|
|
3
|
-
import { isPublicRequest } from '../authentication/tokens/index.js'
|
|
4
|
-
import { hasModuleAccess } from './access.js'
|
|
5
|
-
import { normalizeModuleAccess } from './module-access-resolution.js'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Creates a Hapi plugin that guards module access based on user permissions.
|
|
9
|
-
* Blocks requests that lack sufficient module-level permissions.
|
|
10
|
-
*
|
|
11
|
-
* @param {object} options - Configuration options
|
|
12
|
-
* @param {string} options.assetPath - Path prefix for public assets that bypass authentication
|
|
13
|
-
* @param {ModuleAccess|Module} options.moduleAccess - Module access requirements or module object
|
|
14
|
-
* @returns {object} Hapi plugin object with moduleAccessGuard
|
|
15
|
-
* @throws {Error} When module access configuration cannot be resolved
|
|
16
|
-
*/
|
|
17
|
-
export function createModuleAccessGuard({ assetPath, moduleAccess }) {
|
|
18
|
-
const resolvedModuleAccess = normalizeModuleAccess(moduleAccess)
|
|
19
|
-
|
|
20
|
-
if (!resolvedModuleAccess) {
|
|
21
|
-
throw new Error('Unable to resolve module access configuration')
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
return {
|
|
25
|
-
plugin: {
|
|
26
|
-
name: 'moduleAccessGuard',
|
|
27
|
-
register(server) {
|
|
28
|
-
server.ext('onPreAuth', (request, h) => {
|
|
29
|
-
if (isPublicRequest(request, assetPath)) {
|
|
30
|
-
return h.continue
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
if (hasModuleAccess(request.app?.hubAuth, resolvedModuleAccess)) {
|
|
34
|
-
return h.continue
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
return Boom.forbidden()
|
|
38
|
-
})
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|