-
Notifications
You must be signed in to change notification settings - Fork 537
/
back-end-construct.ts
229 lines (207 loc) · 8.24 KB
/
back-end-construct.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import * as path from "path";
import { LambdaRestApiProps, RestApi } from "aws-cdk-lib/aws-apigateway";
import {
AllowedMethods,
CacheHeaderBehavior,
CachePolicy,
CacheQueryStringBehavior,
DistributionProps,
IOrigin,
OriginRequestPolicy,
OriginSslPolicy,
PriceClass,
ViewerProtocolPolicy,
} from "aws-cdk-lib/aws-cloudfront";
import { HttpOrigin } from "aws-cdk-lib/aws-cloudfront-origins";
import { Policy, PolicyStatement, Role, ServicePrincipal } from "aws-cdk-lib/aws-iam";
import { Runtime } from "aws-cdk-lib/aws-lambda";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { LogGroup, RetentionDays } from "aws-cdk-lib/aws-logs";
import { IBucket } from "aws-cdk-lib/aws-s3";
import { ArnFormat, Aws, Duration, Lazy, Stack } from "aws-cdk-lib";
import { Construct } from "constructs";
import { CloudFrontToApiGatewayToLambda } from "@aws-solutions-constructs/aws-cloudfront-apigateway-lambda";
import { addCfnSuppressRules } from "../../utils/utils";
import { SolutionConstructProps } from "../types";
import * as api from "aws-cdk-lib/aws-apigateway";
export interface BackEndProps extends SolutionConstructProps {
readonly solutionVersion: string;
readonly solutionName: string;
readonly secretsManagerPolicy: Policy;
readonly logsBucket: IBucket;
readonly uuid: string;
readonly cloudFrontPriceClass: string;
}
export class BackEnd extends Construct {
public domainName: string;
constructor(scope: Construct, id: string, props: BackEndProps) {
super(scope, id);
const imageHandlerLambdaFunctionRole = new Role(this, "ImageHandlerFunctionRole", {
assumedBy: new ServicePrincipal("lambda.amazonaws.com"),
path: "/",
});
props.secretsManagerPolicy.attachToRole(imageHandlerLambdaFunctionRole);
const imageHandlerLambdaFunctionRolePolicy = new Policy(this, "ImageHandlerFunctionPolicy", {
statements: [
new PolicyStatement({
actions: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
resources: [
Stack.of(this).formatArn({
service: "logs",
resource: "log-group",
resourceName: "/aws/lambda/*",
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
],
}),
new PolicyStatement({
actions: ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
resources: [
Stack.of(this).formatArn({
service: "s3",
resource: "*",
region: "",
account: "",
}),
],
}),
new PolicyStatement({
actions: ["rekognition:DetectFaces", "rekognition:DetectModerationLabels"],
resources: ["*"],
}),
],
});
addCfnSuppressRules(imageHandlerLambdaFunctionRolePolicy, [
{ id: "W12", reason: "rekognition:DetectFaces requires '*' resources." },
]);
imageHandlerLambdaFunctionRole.attachInlinePolicy(imageHandlerLambdaFunctionRolePolicy);
const imageHandlerLambdaFunction = new NodejsFunction(this, "ImageHandlerLambdaFunction", {
description: `${props.solutionName} (${props.solutionVersion}): Performs image edits and manipulations`,
memorySize: 1024,
runtime: Runtime.NODEJS_20_X,
timeout: Duration.seconds(29),
role: imageHandlerLambdaFunctionRole,
entry: path.join(__dirname, "../../../image-handler/index.ts"),
environment: {
AUTO_WEBP: props.autoWebP,
CORS_ENABLED: props.corsEnabled,
CORS_ORIGIN: props.corsOrigin,
SOURCE_BUCKETS: props.sourceBuckets,
REWRITE_MATCH_PATTERN: "",
REWRITE_SUBSTITUTION: "",
ENABLE_SIGNATURE: props.enableSignature,
SECRETS_MANAGER: props.secretsManager,
SECRET_KEY: props.secretsManagerKey,
ENABLE_DEFAULT_FALLBACK_IMAGE: props.enableDefaultFallbackImage,
DEFAULT_FALLBACK_IMAGE_BUCKET: props.fallbackImageS3Bucket,
DEFAULT_FALLBACK_IMAGE_KEY: props.fallbackImageS3KeyBucket,
},
bundling: {
externalModules: ["sharp"],
nodeModules: ["sharp"],
commandHooks: {
beforeBundling(inputDir: string, outputDir: string): string[] {
return [];
},
beforeInstall(inputDir: string, outputDir: string): string[] {
return [];
},
afterBundling(inputDir: string, outputDir: string): string[] {
return [`cd ${outputDir}`, "rm -rf node_modules/sharp && npm install --arch=x64 --platform=linux sharp"];
},
},
},
});
const imageHandlerLogGroup = new LogGroup(this, "ImageHandlerLogGroup", {
logGroupName: `/aws/lambda/${imageHandlerLambdaFunction.functionName}`,
retention: props.logRetentionPeriod as RetentionDays,
});
addCfnSuppressRules(imageHandlerLogGroup, [
{
id: "W84",
reason: "CloudWatch log group is always encrypted by default.",
},
]);
const cachePolicy = new CachePolicy(this, "CachePolicy", {
cachePolicyName: `ServerlessImageHandler-${props.uuid}`,
defaultTtl: Duration.days(1),
minTtl: Duration.seconds(1),
maxTtl: Duration.days(365),
enableAcceptEncodingGzip: false,
headerBehavior: CacheHeaderBehavior.allowList("origin", "accept"),
queryStringBehavior: CacheQueryStringBehavior.allowList("signature"),
});
const originRequestPolicy = new OriginRequestPolicy(this, "OriginRequestPolicy", {
originRequestPolicyName: `ServerlessImageHandler-${props.uuid}`,
headerBehavior: CacheHeaderBehavior.allowList("origin", "accept"),
queryStringBehavior: CacheQueryStringBehavior.allowList("signature"),
});
const apiGatewayRestApi = RestApi.fromRestApiId(
this,
"ApiGatewayRestApi",
Lazy.string({
produce: () => imageHandlerCloudFrontApiGatewayLambda.apiGateway.restApiId,
})
);
const origin: IOrigin = new HttpOrigin(`${apiGatewayRestApi.restApiId}.execute-api.${Aws.REGION}.amazonaws.com`, {
originPath: "/image",
originSslProtocols: [OriginSslPolicy.TLS_V1_1, OriginSslPolicy.TLS_V1_2],
});
const cloudFrontDistributionProps: DistributionProps = {
comment: "Image Handler Distribution for Serverless Image Handler",
defaultBehavior: {
origin,
allowedMethods: AllowedMethods.ALLOW_GET_HEAD,
viewerProtocolPolicy: ViewerProtocolPolicy.HTTPS_ONLY,
originRequestPolicy,
cachePolicy,
},
priceClass: props.cloudFrontPriceClass as PriceClass,
enableLogging: true,
logBucket: props.logsBucket,
logFilePrefix: "api-cloudfront/",
errorResponses: [
{ httpStatus: 500, ttl: Duration.minutes(10) },
{ httpStatus: 501, ttl: Duration.minutes(10) },
{ httpStatus: 502, ttl: Duration.minutes(10) },
{ httpStatus: 503, ttl: Duration.minutes(10) },
{ httpStatus: 504, ttl: Duration.minutes(10) },
],
};
const logGroupProps = {
retention: props.logRetentionPeriod as RetentionDays,
};
const apiGatewayProps: LambdaRestApiProps = {
handler: imageHandlerLambdaFunction,
deployOptions: {
stageName: "image",
},
binaryMediaTypes: ["*/*"],
defaultMethodOptions: {
authorizationType: api.AuthorizationType.NONE,
},
};
const imageHandlerCloudFrontApiGatewayLambda = new CloudFrontToApiGatewayToLambda(
this,
"ImageHandlerCloudFrontApiGatewayLambda",
{
existingLambdaObj: imageHandlerLambdaFunction,
insertHttpSecurityHeaders: false,
logGroupProps,
cloudFrontDistributionProps,
apiGatewayProps,
}
);
addCfnSuppressRules(imageHandlerCloudFrontApiGatewayLambda.apiGateway, [
{
id: "W59",
reason:
"AWS::ApiGateway::Method AuthorizationType is set to 'NONE' because API Gateway behind CloudFront does not support AWS_IAM authentication",
},
]);
imageHandlerCloudFrontApiGatewayLambda.apiGateway.node.tryRemoveChild("Endpoint"); // we don't need the RestApi endpoint in the outputs
this.domainName = imageHandlerCloudFrontApiGatewayLambda.cloudFrontWebDistribution.distributionDomainName;
}
}