@defra/lis-hubs-infra-access 0.37.0 → 0.38.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-access",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "description": "Shared hub access and capability resolution for the livestock platform.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,6 +22,51 @@ const Forbidden = 403
22
22
 
23
23
  const DEFAULT_NOT_AUTHORISED_PATH = '/auth/not-authorised'
24
24
 
25
+ // RFC 6749 section 4.1.2.1 and OIDC Core section 3.1.2.6
26
+ const KNOWN_IDP_ERRORS = new Set([
27
+ 'invalid_request',
28
+ 'unauthorized_client',
29
+ 'access_denied',
30
+ 'unsupported_response_type',
31
+ 'invalid_scope',
32
+ 'server_error',
33
+ 'temporarily_unavailable',
34
+ 'interaction_required',
35
+ 'login_required',
36
+ 'account_selection_required',
37
+ 'consent_required',
38
+ 'invalid_request_uri',
39
+ 'invalid_request_object',
40
+ 'request_not_supported',
41
+ 'request_uri_not_supported',
42
+ 'registration_not_supported'
43
+ ])
44
+ const PROVIDER_CODE_PATTERN = /\b(AAD(?:B2C|STS)\d+)\b/
45
+
46
+ function toKnownIdpError(value) {
47
+ return typeof value === 'string' && KNOWN_IDP_ERRORS.has(value)
48
+ ? value
49
+ : 'unknown'
50
+ }
51
+
52
+ function toProviderCode(description) {
53
+ if (typeof description !== 'string') {
54
+ return undefined
55
+ }
56
+
57
+ const [, providerCode] = PROVIDER_CODE_PATTERN.exec(description) ?? []
58
+
59
+ return providerCode
60
+ }
61
+
62
+ function createIdpError(query) {
63
+ const idpError = toKnownIdpError(query.error)
64
+ const providerCode = toProviderCode(query.error_description)
65
+ const suffix = providerCode ? ` (${providerCode})` : ''
66
+
67
+ return Boom.badRequest(`Identity provider returned ${idpError}${suffix}`)
68
+ }
69
+
25
70
  /**
26
71
  * Builds the shared response for a hub-level refusal. Authentication and
27
72
  * authorisation are kept apart: the user stays signed in to the hub, but no
@@ -136,7 +181,7 @@ function createCallbackController({
136
181
  },
137
182
  async handler(request, h) {
138
183
  if (request.query?.error) {
139
- throw new Error(request.query?.error_description ?? request.query.error)
184
+ throw createIdpError(request.query)
140
185
  }
141
186
 
142
187
  const grant = await completeAuthorizationCodeGrant(request)
@@ -12,11 +12,33 @@ import {
12
12
  import { getReturnUrlFromRequest, sanitizeReturnUrl } from './tokens/index.js'
13
13
  import { logger } from '@defra/lis-hubs-infra-core'
14
14
 
15
+ const OAUTH_ERROR_PATTERN = /^[a-z_]{1,64}$/
16
+
17
+ /**
18
+ * Reads only the OAuth `error` code from a failed response body. Other body
19
+ * fields (e.g. error_description) are free text and are never read.
20
+ * @param {Response} response
21
+ * @returns {Promise<string | undefined>}
22
+ */
23
+ async function readOAuthErrorCode(response) {
24
+ try {
25
+ const body = await response.json()
26
+ return typeof body?.error === 'string' &&
27
+ OAUTH_ERROR_PATTERN.test(body.error)
28
+ ? body.error
29
+ : undefined
30
+ } catch {
31
+ return undefined
32
+ }
33
+ }
34
+
15
35
  async function fetchJson(url, options = {}) {
16
36
  const response = await fetch(url, options)
17
37
 
18
38
  if (!response.ok) {
19
- throw new Error(`Failed to fetch ${url}: ${response.status}`)
39
+ const oauthError = await readOAuthErrorCode(response)
40
+ const suffix = oauthError ? ` ${oauthError}` : ''
41
+ throw new Error(`Failed to fetch ${url}: ${response.status}${suffix}`)
20
42
  }
21
43
 
22
44
  return response.json()
@@ -2,11 +2,18 @@
2
2
  import { TextEncoder } from 'node:util'
3
3
 
4
4
  import { SignJWT, jwtVerify } from 'jose'
5
+ import { logger } from '@defra/lis-hubs-infra-core'
5
6
 
6
7
  import { AUTHORIZATION_VERSION } from '../../authorization/constants.js'
7
8
 
8
9
  const encoder = new TextEncoder()
9
10
  const MILLISECONDS_PER_SECOND = 1000
11
+ const JWT_EXPIRED_CODE = 'ERR_JWT_EXPIRED'
12
+ const AUTHZ_VERSION_UNSUPPORTED_CODE = 'ERR_AUTHZ_VERSION_UNSUPPORTED'
13
+ const ROUTINE_FAILURE_CODES = new Set([
14
+ JWT_EXPIRED_CODE,
15
+ AUTHZ_VERSION_UNSUPPORTED_CODE
16
+ ])
10
17
 
11
18
  function getHubJwtSecret(secret) {
12
19
  return encoder.encode(secret)
@@ -72,7 +79,9 @@ export async function verifyHubJwt(token, { secret, issuer, audience }) {
72
79
  })
73
80
 
74
81
  if (payload.authzVersion !== AUTHORIZATION_VERSION) {
75
- throw new Error('Unsupported authorization model version')
82
+ const error = new Error('Unsupported authorization model version')
83
+ error.code = AUTHZ_VERSION_UNSUPPORTED_CODE
84
+ throw error
76
85
  }
77
86
 
78
87
  return payload
@@ -111,7 +120,19 @@ export async function getHubJwtPayloadFromRequest(
111
120
 
112
121
  try {
113
122
  return await verifyHubJwt(token, { secret, issuer, audience })
114
- } catch {
123
+ } catch (error) {
124
+ if (!ROUTINE_FAILURE_CODES.has(error?.code)) {
125
+ // error.payload carries the decoded token, so the error is never logged whole
126
+ logger.warn(
127
+ {
128
+ code: error?.code,
129
+ claim: error?.claim,
130
+ reason: error?.reason,
131
+ name: error?.name
132
+ },
133
+ 'Hub JWT verification failed'
134
+ )
135
+ }
115
136
  return null
116
137
  }
117
138
  }