/
createAuthScheme.js
254 lines (217 loc) · 7.68 KB
/
createAuthScheme.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import { join } from 'path'
import Boom from '@hapi/boom'
import authCanExecuteResource from './authCanExecuteResource.js'
import debugLog from '../../debugLog.js'
import HandlerRunner from '../../lambda/handler-runner/index.js'
import LambdaContext from '../../lambda/LambdaContext.js'
import serverlessLog from '../../serverlessLog.js'
import {
nullIfEmpty,
parseHeaders,
parseMultiValueHeaders,
parseMultiValueQueryStringParameters,
parseQueryStringParameters,
splitHandlerPathAndName,
} from '../../utils/index.js'
export default function createAuthScheme(
authFun,
authorizerOptions,
functionName,
endpointPath,
options,
servicePath,
provider,
) {
const authFunName = authorizerOptions.name
let identityHeader = 'authorization'
if (authorizerOptions.type !== 'request') {
const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(
authorizerOptions.identitySource,
)
if (!identitySourceMatch || identitySourceMatch.length !== 2) {
throw new Error(
`Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`,
)
}
identityHeader = identitySourceMatch[1].toLowerCase()
}
const { handler, memorySize, runtime, timeout } = authFun
const [handlerPath, handlerName] = splitHandlerPathAndName(handler)
const funOptions = {
functionKey: functionName,
handlerName, // i.e. run
handlerPath: join(servicePath, handlerPath),
memorySize,
runtime: runtime || provider.runtime,
timeout: (timeout || 30) * 1000,
}
// Create Auth Scheme
return () => ({
authenticate(request, h) {
// TODO FIXME, should use LambdaFunction
const env = {
...provider.environment,
...authFun.environment,
...process.env,
}
console.log('') // Just to make things a little pretty
serverlessLog(
`Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`,
)
// Get Authorization header
const { req } = request.raw
// Get path params
// aws doesn't auto decode path params - hapi does
const pathParams = { ...request.params }
let event
// Create event Object for authFunction
// methodArn is the ARN of the function we are running we are authorizing access to (or not)
// Account ID and API ID are not simulated
if (authorizerOptions.type === 'request') {
const { rawHeaders, url } = req
event = {
headers: parseHeaders(rawHeaders),
httpMethod: request.method.toUpperCase(),
multiValueHeaders: parseMultiValueHeaders(rawHeaders),
multiValueQueryStringParameters: parseMultiValueQueryStringParameters(
url,
),
path: request.path,
pathParameters: nullIfEmpty(pathParams),
queryStringParameters: parseQueryStringParameters(url),
type: 'REQUEST',
}
} else {
const authorization = req.headers[identityHeader]
const identityValidationExpression = new RegExp(
authorizerOptions.identityValidationExpression,
)
const matchedAuthorization = identityValidationExpression.test(
authorization,
)
const finalAuthorization = matchedAuthorization ? authorization : ''
debugLog(`Retrieved ${identityHeader} header "${finalAuthorization}"`)
event = {
authorizationToken: finalAuthorization,
type: 'TOKEN',
}
}
const httpMethod = request.method.toUpperCase()
const apiId = 'random-api-id'
const accountId = 'random-account-id'
const resourcePath = request.path.replace(
new RegExp(`^/${provider.stage}`),
'',
)
event.methodArn = `arn:aws:execute-api:${provider.region}:${accountId}:${apiId}/${provider.stage}/${httpMethod}${resourcePath}`
event.enhancedAuthContext = {}
event.requestContext = {
accountId,
apiId,
httpMethod,
requestId: 'random-request-id',
resourceId: 'random-resource-id',
resourcePath,
stage: provider.stage,
}
let handlerRunner
// Create the Authorization function handler
try {
// TODO FIXME, should use LambdaFunction
handlerRunner = new HandlerRunner(funOptions, options, env)
} catch (err) {
debugLog(`create authorization function handler error: ${err}`)
throw Boom.badImplementation(
null,
`Error while loading ${authFunName}: ${err.message}`,
)
}
return new Promise((resolve, reject) => {
const callback = (err, data) => {
// Return an unauthorized response
const onError = (error) => {
serverlessLog(
`Authorization function returned an error response: (λ: ${authFunName})`,
error,
)
return reject(Boom.unauthorized('Unauthorized'))
}
if (err) {
onError(err)
return
}
const onSuccess = (policy) => {
// Validate that the policy document has the principalId set
if (!policy.principalId) {
serverlessLog(
`Authorization response did not include a principalId: (λ: ${authFunName})`,
err,
)
return reject(
Boom.forbidden('No principalId set on the Response'),
)
}
if (
!authCanExecuteResource(policy.policyDocument, event.methodArn)
) {
serverlessLog(
`Authorization response didn't authorize user to access resource: (λ: ${authFunName})`,
err,
)
return reject(
Boom.forbidden(
'User is not authorized to access this resource',
),
)
}
serverlessLog(
`Authorization function returned a successful response: (λ: ${authFunName})`,
)
const authorizer = {
integrationLatency: '42',
principalId: policy.principalId,
...policy.context,
}
// Set the credentials for the rest of the pipeline
return resolve(
h.authenticated({
credentials: {
authorizer,
context: policy.context,
principalId: policy.principalId,
usageIdentifierKey: policy.usageIdentifierKey,
},
}),
)
}
if (data && typeof data.then === 'function') {
debugLog('Auth function returned a promise')
data.then(onSuccess).catch(onError)
} else if (data instanceof Error) {
onError(data)
} else {
onSuccess(data)
}
}
// TODO FIXME this should just use the LambdaFunction class
// Creat the Lambda Context for the Auth function
const lambdaContext = new LambdaContext({
callback,
functionName: authFun.name,
memorySize: authFun.memorySize || provider.memorySize,
timeout: authFun.timeout || provider.timeout,
})
// TODO FIXME this should just use the LambdaFunction class
const result = handlerRunner.run(event, lambdaContext, callback)
// Promise support
if (result && typeof result.then === 'function') {
result
.then((data) => callback(null, data))
.catch((err) => callback(err, null))
} else if (result instanceof Error) {
callback(result, null)
}
})
},
})
}