-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathlambdaAuthorizer.ts
359 lines (312 loc) · 13.3 KB
/
lambdaAuthorizer.ts
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// These APIs are currently experimental and may change.
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import * as awslambda from "aws-lambda";
import { CognitoAuthorizer } from "./cognitoAuthorizer";
import * as utils from "../utils";
export type AuthorizerEvent = awslambda.CustomAuthorizerEvent;
export type AuthorizerResponse = awslambda.CustomAuthorizerResult;
export type AuthResponseContext = awslambda.AuthResponseContext;
/**
* LambdaAuthorizer provides the definition for a custom Authorizer for API Gateway.
*/
export interface LambdaAuthorizer {
/**
* The name for the Authorizer to be referenced as. This must be unique for each unique
* authorizer within the API. If no name if specified, a name will be generated for you.
*/
authorizerName?: string;
/**
* parameterName is the name of the header or query parameter containing the authorization
* token. Must be "Unused" for multiple identity sources.
* */
parameterName: string;
/**
* Defines where in the request API Gateway should look for identity information. The value must
* be "header" or "query". If there are multiple identity sources, the value must be "header".
*/
parameterLocation: "header" | "query";
/**
* Specifies the authorization mechanism for the client. Typical values are "oauth2" or "custom".
*/
authType: string;
/**
* The type of the authorizer. This value must be one of the following:
* - "token", for an authorizer with the caller identity embedded in an authorization token
* - "request", for an authorizer with the caller identity contained in request parameters
*/
type: "token" | "request";
/**
* The authorizerHandler specifies information about the authorizing Lambda. You can either set
* up the Lambda separately and just provide the required information or you can define the
* Lambda inline using a JavaScript function.
*/
handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>;
/**
* List of mapping expressions of the request parameters as the identity source. This indicates
* where in the request identity information is expected. Applicable for the authorizer of the
* "request" type only. Example: ["method.request.header.HeaderAuth1",
* "method.request.querystring.QueryString1"]
*/
identitySource?: string[];
/**
* A regular expression for validating the token as the incoming identity. It only invokes the
* authorizer's lambda if there is a match, else it will return a 401. This does not apply to
* REQUEST Lambda Authorizers. Example: "^x-[a-z]+"
*/
identityValidationExpression?: string;
/**
* The number of seconds during which the resulting IAM policy is cached. Default is 300s. You
* can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an
* authorizer across more than one route you will want to disable the cache or else it will
* cause problems for you.
*/
authorizerResultTtlInSeconds?: number;
}
export interface LambdaAuthorizerInfo {
/**
* The Uniform Resource Identifier (URI) of the authorizer Lambda function. The Lambda may also
* be passed directly, in which cases the URI will be obtained for you.
*/
uri: pulumi.Input<string> | aws.lambda.Function;
/**
* Credentials required for invoking the authorizer in the form of an ARN of an IAM execution role.
* For example, "arn:aws:iam::account-id:IAM_role".
*/
credentials: pulumi.Input<string> | aws.iam.Role;
}
/** @internal */
export function isLambdaAuthorizer(authorizer: LambdaAuthorizer | CognitoAuthorizer): authorizer is LambdaAuthorizer {
return (<LambdaAuthorizer>authorizer).handler !== undefined;
}
/** @internal */
export function isLambdaAuthorizerInfo(info: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>): info is LambdaAuthorizerInfo {
return (<LambdaAuthorizerInfo>info).uri !== undefined;
}
/** @internal */
export function getIdentitySource(identitySources: string[] | undefined): string {
if (identitySources) {
return identitySources.join(", ");
}
return "";
}
/** @internal */
export function createRoleWithAuthorizerInvocationPolicy(
authorizerName: string, authorizerLambda: aws.lambda.Function,
opts: pulumi.CustomResourceOptions): aws.iam.Role {
const policy = aws.iam.assumeRolePolicyForPrincipal({ "Service": ["lambda.amazonaws.com", "apigateway.amazonaws.com"] });
// We previously didn't parent the Role or RolePolicy to anything. Now we do. Pass an
// appropriate alias to prevent resources from being destroyed/created.
const role = new aws.iam.Role(authorizerName + "-authorizer-role", {
assumeRolePolicy: JSON.stringify(policy),
}, pulumi.mergeOptions(opts, { aliases: [{ parent: pulumi.rootStackResource }] }));
// Add invocation policy to lambda role
const invocationPolicy = new aws.iam.RolePolicy(authorizerName + "-invocation-policy", {
policy: pulumi.interpolate`{
"Version": "2012-10-17",
"Statement": [
{
"Action": "lambda:InvokeFunction",
"Effect": "Allow",
"Resource": "${authorizerLambda.arn}"
}
]
}`,
role: role.id,
}, pulumi.mergeOptions(opts, { aliases: [{ parent: pulumi.rootStackResource }] }));
return role;
}
/**
* Simplifies creating an AuthorizerResponse.
*
* @param principalId - unique identifier for the user
* @param effect - whether to "Allow" or "Deny" the request
* @param resource - the API method to be invoked (typically event.methodArn)
* @param context - key-value pairs that are passed from the authorizer to the backend Lambda
* @param apiKey - if the API uses a usage plan, this must be set to one of the usage plan's API keys
*/
export function authorizerResponse(principalId: string, effect: Effect, resource: string, context?: AuthResponseContext, apiKey?: string): AuthorizerResponse {
const response: AuthorizerResponse = {
principalId: principalId,
policyDocument: {
Version: "2012-10-17",
Statement: [{
Action: "execute-api:Invoke",
Effect: effect,
Resource: resource,
}],
},
};
response.context = context;
response.usageIdentifierKey = apiKey;
return response;
}
export type Effect = "Allow" | "Deny";
/**
* The set of arguments for constructing a token LambdaAuthorizer resource.
*/
export interface TokenAuthorizerArgs {
/**
* The name for the Authorizer to be referenced as. This must be unique for each unique
* authorizer within the API. If no name if specified, a name will be generated for you.
*/
authorizerName?: string;
/**
* The request header for the authorization token. If not set, this defaults to
* Authorization.
*/
header?: string;
/**
* The authorizerHandler specifies information about the authorizing Lambda. You can either set
* up the Lambda separately and just provide the required information or you can define the
* Lambda inline using a JavaScript function.
*/
handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>;
/**
* A regular expression for validating the token as the incoming identity.
* Example: "^x-[a-z]+"
*/
identityValidationExpression?: string;
/**
* The number of seconds during which the resulting IAM policy is cached. Default is 300s. You
* can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an
* authorizer across more than one route you will want to disable the cache or else it will
* cause problems for you.
*/
authorizerResultTtlInSeconds?: number;
}
/**
* getTokenLambdaAuthorizer is a helper function to generate a token LambdaAuthorizer.
* @param name - the name for the authorizer. This must be unique for each unique authorizer in the API.
* @param args - configuration information for the token Lambda.
*/
export function getTokenLambdaAuthorizer(args: TokenAuthorizerArgs): LambdaAuthorizer {
return {
authorizerName: args.authorizerName,
parameterName: args.header || "Authorization",
parameterLocation: "header",
authType: "oauth2",
type: "token",
handler: args.handler,
identityValidationExpression: args.identityValidationExpression,
authorizerResultTtlInSeconds: args.authorizerResultTtlInSeconds,
};
}
/**
* The set of arguments for constructing a request LambdaAuthorizer resource.
*/
export interface RequestAuthorizerArgs {
/**
* The name for the Authorizer to be referenced as. This must be unique for each unique authorizer
* within the API. If no name if specified, a name will be generated for you.
*/
authorizerName?: string;
/**
* queryParameters is an array of the expected query parameter keys used to authorize a request.
* While this argument is optional, at least one queryParameter or one header must be defined.
* */
queryParameters?: string[];
/**
* headers is an array of the expected header keys used to authorize a request.
* While this argument is optional, at least one queryParameter or one header must be defined.
* */
headers?: string[];
/**
* The authorizerHandler specifies information about the authorizing Lambda. You can either set
* up the Lambda separately and just provide the required information or you can define the
* Lambda inline using a JavaScript function.
*/
handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>;
/**
* The number of seconds during which the resulting IAM policy is cached. Default is 300s. You
* can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an
* authorizer across more than one route you will want to disable the cache or else it will
* cause problems for you.
*/
authorizerResultTtlInSeconds?: number;
}
/**
* getRequestLambdaAuthorizer is a helper function to generate a request LambdaAuthorizer.
*
* @param name - the name for the authorizer. This must be unique for each unique authorizer in the
* API.
* @param args - configuration information for the token Lambda.
*/
export function getRequestLambdaAuthorizer(args: RequestAuthorizerArgs): LambdaAuthorizer {
let parameterName: string;
let location: "header" | "query";
const numQueryParams = getLength(args.queryParameters);
const numHeaders = getLength(args.headers);
if (numQueryParams === 0 && numHeaders === 0) {
throw new Error("[args.queryParameters] and [args.headers] were both empty. At least one query parameter or header must be specified");
} else {
location = getLocation(numHeaders, numQueryParams);
parameterName = getParameterName(args, numHeaders, numQueryParams);
}
return {
authorizerName: args.authorizerName,
parameterName: parameterName,
parameterLocation: location,
authType: "custom",
type: "request",
handler: args.handler,
identitySource: parametersToIdentitySources(args),
authorizerResultTtlInSeconds: args.authorizerResultTtlInSeconds,
};
}
/** @internal */
function getLength(params: string[] | undefined): number {
if (!params) {
return 0;
}
return params.length;
}
/** @internal */
function getParameterName(args: RequestAuthorizerArgs, numHeaders: number, numQueryParameters: number): string {
if (numQueryParameters + numHeaders === 1) {
if (args.queryParameters) {
return args.queryParameters[0];
} else if (args.headers) {
return args.headers[0];
}
}
return "Unused";
}
/** @internal */
function getLocation(numHeaders: number, numQueryParameters: number): "header" | "query" {
if (numHeaders > 0) {
return "header";
} else if (numQueryParameters > 0) {
return "query";
} else {
throw new Error("Could not determine parameter location");
}
}
/** @internal */
function parametersToIdentitySources(args: RequestAuthorizerArgs): string[] {
const identitySource: string[] = [];
if (args.headers) {
for (const header of args.headers) {
identitySource.push("method.request.header." + header);
}
}
if (args.queryParameters) {
for (const param of args.queryParameters) {
identitySource.push("method.request.querystring." + param);
}
}
return identitySource;
}