-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathservice.ts
More file actions
177 lines (162 loc) · 6.07 KB
/
service.ts
File metadata and controls
177 lines (162 loc) · 6.07 KB
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
import { Construct } from 'constructs';
import { Aws, Duration } from 'aws-cdk-lib';
import { FunctionUrlAuthType, Function, InvokeMode, CfnPermission } from 'aws-cdk-lib/aws-lambda';
import {
AllowedMethods,
CacheCookieBehavior,
CacheHeaderBehavior,
CachePolicy,
CacheQueryStringBehavior,
Distribution,
LambdaEdgeEventType,
OriginRequestPolicy,
SecurityPolicyProtocol,
} from 'aws-cdk-lib/aws-cloudfront';
import { FunctionUrlOrigin } from 'aws-cdk-lib/aws-cloudfront-origins';
import { StringParameter } from 'aws-cdk-lib/aws-ssm';
import { ARecord, IHostedZone, RecordTarget } from 'aws-cdk-lib/aws-route53';
import { CloudFrontTarget } from 'aws-cdk-lib/aws-route53-targets';
import { ICertificate } from 'aws-cdk-lib/aws-certificatemanager';
import { Bucket } from 'aws-cdk-lib/aws-s3';
import { EdgeFunction } from './edge-function';
import { AwsCustomResource, PhysicalResourceId, AwsCustomResourcePolicy } from 'aws-cdk-lib/custom-resources';
export interface CloudFrontLambdaFunctionUrlServiceProps {
/**
* Subdomain name for the service. If not specified, the root domain will be used.
*
* @default use root domain
*/
subDomain?: string;
handler: Function;
/**
* This should be unique across the app
*/
serviceName: string;
/**
* @default basic auth is disabled
*/
basicAuthUsername?: string;
basicAuthPassword?: string;
/**
* Route 53 hosted zone for custom domain.
*
* @default No custom domain. CloudFront's default domain will be used.
*/
hostedZone?: IHostedZone;
/**
* ACM certificate for custom domain (must be in us-east-1 for CloudFront).
*
* @default No custom domain.
*/
certificate?: ICertificate;
signPayloadHandler: EdgeFunction;
accessLogBucket: Bucket;
}
export class CloudFrontLambdaFunctionUrlService extends Construct {
public readonly urlParameter: StringParameter;
public readonly url: string;
public readonly domainName: string;
constructor(scope: Construct, id: string, props: CloudFrontLambdaFunctionUrlServiceProps) {
super(scope, id);
const { handler, serviceName, subDomain, hostedZone, certificate, accessLogBucket, signPayloadHandler } = props;
let domainName = '';
if (hostedZone) {
domainName = subDomain ? `${subDomain}.${hostedZone.zoneName}` : hostedZone.zoneName;
}
const furl = handler.addFunctionUrl({
authType: FunctionUrlAuthType.AWS_IAM,
invokeMode: InvokeMode.RESPONSE_STREAM,
});
const origin = FunctionUrlOrigin.withOriginAccessControl(furl, {
connectionTimeout: Duration.seconds(6),
readTimeout: Duration.seconds(60),
});
const cachePolicy = new CachePolicy(this, 'SharedCachePolicy', {
queryStringBehavior: CacheQueryStringBehavior.all(),
headerBehavior: CacheHeaderBehavior.allowList(
// CachePolicy.USE_ORIGIN_CACHE_CONTROL_HEADERS_QUERY_STRINGS contains Host header here,
// making it impossible to use with API Gateway
'authorization',
'Origin',
'X-HTTP-Method-Override',
'X-HTTP-Method',
'X-Method-Override',
// Next.js App Router RSC headers to prevent cache poisoning.
// Without these, RSC flight responses (text/x-component) and HTML responses
// share the same cache key, causing wrong content to be served.
'RSC',
'Next-Router-Prefetch',
'Next-Router-State-Tree',
'Next-URL',
),
defaultTtl: Duration.seconds(0),
cookieBehavior: CacheCookieBehavior.all(),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
});
const distribution = new Distribution(this, 'Resource', {
comment: `CloudFront for ${serviceName}`,
defaultBehavior: {
origin,
cachePolicy,
allowedMethods: AllowedMethods.ALLOW_ALL,
originRequestPolicy: OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
edgeLambdas: [
{
functionVersion: signPayloadHandler.versionArn(this),
eventType: LambdaEdgeEventType.ORIGIN_REQUEST,
includeBody: true,
},
],
},
// errorResponses: [{ httpStatus: 404, responsePagePath: '/', responseHttpStatus: 200 }],
logBucket: accessLogBucket,
logFilePrefix: `${serviceName}/`,
...(hostedZone ? { certificate: certificate, domainNames: [domainName] } : {}),
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
});
// Starting October 2025, new function URLs require both lambda:InvokeFunctionUrl
// and lambda:InvokeFunction permissions for CloudFront OAC.
// CDK's FunctionUrlOrigin.withOriginAccessControl only adds lambda:InvokeFunctionUrl,
// so we explicitly add lambda:InvokeFunction here.
// See: https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html
new CfnPermission(this, 'InvokeFunctionPermission', {
action: 'lambda:InvokeFunction',
functionName: handler.functionArn,
principal: 'cloudfront.amazonaws.com',
sourceArn: `arn:${Aws.PARTITION}:cloudfront::${Aws.ACCOUNT_ID}:distribution/${distribution.distributionId}`,
});
if (hostedZone) {
new ARecord(this, 'Record', {
zone: hostedZone,
target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
recordName: subDomain,
});
} else {
domainName = distribution.domainName;
}
// Invalidate CloudFront when Lambda function version changes
new AwsCustomResource(this, 'CloudFrontInvalidation', {
onUpdate: {
service: 'cloudfront',
action: 'createInvalidation',
parameters: {
DistributionId: distribution.distributionId,
InvalidationBatch: {
CallerReference: `${handler.currentVersion.version}`,
Paths: {
Quantity: 1,
Items: ['/*'],
},
},
},
physicalResourceId: PhysicalResourceId.of('invalidation'),
},
policy: AwsCustomResourcePolicy.fromSdkCalls({
resources: [distribution.distributionArn],
}),
});
this.url = `https://${domainName}`;
this.domainName = domainName;
}
}