-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrest-api-gateway-stack.ts
334 lines (300 loc) · 11.3 KB
/
rest-api-gateway-stack.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
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as elbv2 from "aws-cdk-lib/aws-elasticloadbalancingv2";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
import { PassthroughBehavior } from "aws-cdk-lib/aws-apigateway"
import * as cognito from 'aws-cdk-lib/aws-cognito';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as logs from "aws-cdk-lib/aws-logs";
import * as lambdapython from '@aws-cdk/aws-lambda-python-alpha';
import * as ssm from 'aws-cdk-lib/aws-ssm';
import * as iam from 'aws-cdk-lib/aws-iam';
import { IdentityPool, UserPoolAuthenticationProvider } from '@aws-cdk/aws-cognito-identitypool-alpha';
import { NagSuppressions } from 'cdk-nag'
export class RestApiGatewayStack extends cdk.Stack {
public readonly restApi: apigateway.RestApi;
public readonly userPool: cognito.UserPool;
public readonly userPoolClient: cognito.UserPoolClient
public readonly identityPool: IdentityPool;
constructor(
scope: Construct,
id: string,
httpApiInternalNLB: elbv2.NetworkLoadBalancer,
props?: cdk.StackProps
) {
super(scope, id, props);
const link = new apigateway.VpcLink(this, 'link', {
targets: [httpApiInternalNLB],
});
// User Pool
this.userPool = new cognito.UserPool(this, 'userpool', {
userPoolName: 'mlflow-user-pool',
self#Enabled: true,
signInAliases: {
email: true,
},
autoVerify: {
email: false,
},
passwordPolicy: {
minLength: 8,
requireLowercase: true,
requireDigits: true,
requireUppercase: true,
requireSymbols: true,
},
accountRecovery: cognito.AccountRecovery.EMAIL_ONLY,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
const cfnUserPool = this.userPool.node.defaultChild as cognito.CfnUserPool;
cfnUserPool.userPoolAddOns = { advancedSecurityMode: "ENFORCED" };
this.identityPool = new IdentityPool(this, 'mlflow-identity-pool', {
identityPoolName: 'mlflow-identity-pool',
authenticationProviders: {
userPools: [new UserPoolAuthenticationProvider({ userPool: this.userPool })],
},
});
this.userPoolClient = this.userPool.addClient('mlflow-app-client', {
supportedIdentityProviders: [
cognito.UserPoolClientIdentityProvider.COGNITO,
],
});
const defaultProxyApiIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES,
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}/`
}
);
const logGroup = new logs.LogGroup(this, 'MLflowRestApiAccessLogs', {
retention: 30, // Keep logs for 30 days
});
this.restApi = new apigateway.RestApi(this, 'mlflow-rest-api',
{
defaultIntegration: defaultProxyApiIntegration,
defaultMethodOptions: {
methodResponses: [{
statusCode: "200"
}],
authorizationType: apigateway.AuthorizationType.IAM
},
deployOptions: {
accessLogDestination: new apigateway.LogGroupLogDestination(logGroup),
accessLogFormat: apigateway.AccessLogFormat.jsonWithStandardFields(),
loggingLevel: apigateway.MethodLoggingLevel.INFO,
dataTraceEnabled: true
},
cloudWatchRole: true
}
)
const lambdaAuthorizerRole = new iam.Role(this, "lambdaAuthorizerRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
inlinePolicies: {
cloudWatch: new iam.PolicyDocument({
statements:[
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
resources: [`arn:aws:logs:${this.region}:${this.account}:*`],
actions: [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
})
]
}),
}
})
const lambdaFunction = new lambdapython.PythonFunction(this, 'MyFunction', {
entry: './lambda/authorizer/', // required
runtime: lambda.Runtime.PYTHON_3_9, // required
index: 'index.py', // optional, defaults to 'index.py'
handler: 'handler', // optional, defaults to 'handler',
reservedConcurrentExecutions: 100, // change as you see it fit
role: lambdaAuthorizerRole,
environment: {
REGION: this.region,
ACCOUNT: this.account,
COGNITO_USER_POOL_ID: this.userPool.userPoolId,
REST_API_ID: this.restApi.restApiId,
COGNITO_KEYS_URL: `https://cognito-idp.${this.region}.amazonaws.com/${this.userPool.userPoolId}/.well-known/jwks.json`,
APP_CLIENT_ID: this.userPoolClient.userPoolClientId
},
});
const lambdaAuthorizer = new apigateway.RequestAuthorizer(this, 'lambda-authorizer', {
handler: lambdaFunction,
identitySources: [apigateway.IdentitySource.header('Authorization')],
resultsCacheTtl: cdk.Duration.seconds(0) // Increase as you see it fit
});
const proxyApiIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
requestParameters: {
'integration.request.path.proxy': 'method.request.path.proxy'
},
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}:8080/{proxy}`
}
);
const rootProxy = this.restApi.root.addProxy({
defaultIntegration: proxyApiIntegration,
defaultMethodOptions: {
requestParameters: {
'method.request.path.proxy': true
},
authorizer: lambdaAuthorizer,
authorizationType: apigateway.AuthorizationType.CUSTOM,
},
// "false" will require explicitly adding methods on the `proxy` resource
anyMethod: true // "true" is the default
});
const apiIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
requestParameters: {
'integration.request.path.proxy': 'method.request.path.proxy'
},
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}:8080/api/{proxy}`
});
// /api/
const apiResource = this.restApi.root.addResource('api')
apiResource.addProxy({
defaultIntegration: apiIntegration,
defaultMethodOptions: {
requestParameters: {
'method.request.path.proxy': true
},
authorizationType: apigateway.AuthorizationType.IAM,
},
// "false" will require explicitly adding methods on the `proxy` resource
anyMethod: true // "true" is the default
});
const routesApiGatewayIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
requestParameters: {
'integration.request.path.proxy': 'method.request.path.proxy'
},
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}:8081/api/2.0/endpoints/{proxy}`
});
const routesApiGatewayResourse = apiResource.addResource('2.0').addResource('endpoints')
const routesResourceIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}:8081/api/2.0/endpoints/`
});
// // /api/2.0/endpoints/
routesApiGatewayResourse.addMethod(
'ANY',
routesResourceIntegration
)
routesApiGatewayResourse.addProxy({
defaultIntegration: routesApiGatewayIntegration,
defaultMethodOptions: {
requestParameters: {
'method.request.path.proxy': true
},
authorizationType: apigateway.AuthorizationType.IAM,
},
// "false" will require explicitly adding methods on the `proxy` resource
anyMethod: true // "true" is the default
});
// /endpoints/{proxy+}
const gatewayIntegration = new apigateway.Integration(
{
type: apigateway.IntegrationType.HTTP_PROXY,
integrationHttpMethod: 'ANY',
options: {
connectionType: apigateway.ConnectionType.VPC_LINK,
vpcLink: link,
requestParameters: {
'integration.request.path.proxy': 'method.request.path.proxy'
},
passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES
},
uri: `http://${httpApiInternalNLB.loadBalancerDnsName}:8081/endpoints/{proxy}`
});
const gatewayResource = this.restApi.root.addResource('endpoints')
gatewayResource.addProxy({
defaultIntegration: gatewayIntegration,
defaultMethodOptions: {
requestParameters: {
'method.request.path.proxy': true
},
authorizationType: apigateway.AuthorizationType.IAM,
},
// "false" will require explicitly adding methods on the `proxy` resource
anyMethod: true // "true" is the default
});
const mlflowRestApiId = new ssm.StringParameter(this, 'mlflowRestApiId', {
parameterName: 'mlflow-restApiId',
stringValue: this.restApi.restApiId,
});
const mlflowRestApiUrl = new ssm.StringParameter(this, 'mlflowRestApiUrl', {
parameterName: 'mlflow-restApiUrl',
stringValue: this.restApi.url,
});
NagSuppressions.addResourceSuppressions(this.userPool, [
{
id: 'AwsSolutions-COG2',
reason: 'MFA not necessary for this sample'
}
]
)
NagSuppressions.addResourceSuppressions(this.restApi, [
{
id: 'AwsSolutions-APIG2',
reason: 'Request validation is done at a deeper level by the MLflow server'
},
{
id: 'AwsSolutions-IAM4',
reason: 'CloudWatch policy automatically generated',
appliesTo: ['Policy::arn:<AWS::Partition>:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs']
},
{
id: 'AwsSolutions-COG4',
reason: 'The Proxy resource uses either a lambda authorizer (that validates the token with the Cognito User Pool or IAM_AUTH'
}
],
true
)
NagSuppressions.addResourceSuppressions(lambdaAuthorizerRole, [
{
id: 'AwsSolutions-IAM5',
reason: 'Lambda Authorizer permissions to log to CloudWatch',
appliesTo: [`Resource::arn:aws:logs:${this.region}:${this.account}:*`]
}
])
new cdk.CfnOutput(this, "Rest API Output : ", {
value: this.restApi.url,
});
}
}