-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathapp.ts
607 lines (538 loc) · 16.6 KB
/
app.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
import * as codebuild from 'aws-cdk-lib/aws-codebuild';
import * as iam from 'aws-cdk-lib/aws-iam';
import { IResource, Lazy, Resource, SecretValue } from 'aws-cdk-lib/core';
import { Construct } from 'constructs';
import { CfnApp } from 'aws-cdk-lib/aws-amplify';
import { BasicAuth } from './basic-auth';
import { Branch, BranchOptions } from './branch';
import { Domain, DomainOptions } from './domain';
import { renderEnvironmentVariables } from './utils';
import { addConstructMetadata, MethodMetadata } from 'aws-cdk-lib/core/lib/metadata-resource';
/**
* An Amplify Console application
*/
export interface IApp extends IResource {
/**
* The application id
*
* @attribute
*/
readonly appId: string;
}
/**
* Configuration for the source code provider
*/
export interface SourceCodeProviderConfig {
/**
* The full HTTPS URL for the repository for the application.
*
* For GitHub: `https://github.com/owner/repository`
* For GitLab: `https://gitlab.com/owner/repository`
* For CodeCommit: The HTTPS clone URL
*/
readonly repository: string;
/**
* OAuth token for 3rd party source control system for an Amplify App, used
* to create webhook and read-only deploy key. OAuth token is not stored.
*
* For GitHub repositories, use `accessToken` instead. OAuth tokens for GitHub repositories
* are supported for backward compatibility but we strongly recommend using `accessToken`
* with the Amplify GitHub App.
*
* For other repository providers like Bitbucket or CodeCommit, use `oauthToken`.
*
* Either `accessToken` (GitHub) or `oauthToken` (other providers) must be specified
* when connecting to a source code repository.
*
* @default - do not use a token
* @deprecated For GitHub repositories, use accessToken instead
*/
readonly oauthToken?: SecretValue;
/**
* Personal Access token for GitHub repository for an Amplify
* App, used to authorize access to a GitHub repository using the Amplify GitHub App.
* Token is not stored.
*
* This is the recommended way to authorize access to GitHub repositories.
* For non-GitHub repositories (GitLab, Bitbucket, CodeCommit), use `oauthToken`.
*
* Either `accessToken` (GitHub) or `oauthToken` (other providers) must be specified
* when connecting to a source code repository.
*
* @default - do not use a token
*/
readonly accessToken?: SecretValue;
}
/**
* A source code provider
*/
export interface ISourceCodeProvider {
/**
* Binds the source code provider to an app
*
* @param app The app [disable-awslint:ref-via-interface]
*/
bind(app: App): SourceCodeProviderConfig;
}
/**
* Properties for an App
*/
export interface AppProps {
/**
* The name for the application
*
* @default - a CDK generated name
*/
readonly appName?: string;
/**
* The source code provider for this application
*
* @default - not connected to a source code provider
*/
readonly sourceCodeProvider?: ISourceCodeProvider;
/**
* The auto branch creation configuration. Use this to automatically create
* branches that match a certain pattern.
*
* @default - no auto branch creation
*/
readonly autoBranchCreation?: AutoBranchCreation;
/**
* Automatically disconnect a branch in the Amplify Console when you delete a
* branch from your Git repository.
*
* @default false
*/
readonly autoBranchDeletion?: boolean;
/**
* The Basic Auth configuration. Use this to set password protection at an
* app level to all your branches.
*
* @default - no password protection
*/
readonly basicAuth?: BasicAuth;
/**
* BuildSpec for the application. Alternatively, add a `amplify.yml`
* file to the repository.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/build-settings.html
*
* @default - no build spec
*/
readonly buildSpec?: codebuild.BuildSpec;
/**
* The custom HTTP response headers for an Amplify app.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/custom-headers.html
*
* @default - no custom response headers
*/
readonly customResponseHeaders?: CustomResponseHeader[];
/**
* Custom rewrite/redirect rules for the application
*
* @default - no custom rewrite/redirect rules
*/
readonly customRules?: CustomRule[];
/**
* A description for the application
*
* @default - no description
*/
readonly description?: string;
/**
* Environment variables for the application.
*
* All environment variables that you add are encrypted to prevent rogue
* access so you can use them to store secret information.
*
* @default - no environment variables
*/
readonly environmentVariables?: { [name: string]: string };
/**
* The IAM service role to associate with the application. The App
* implements IGrantable.
*
* @default - a new role is created
*/
readonly role?: iam.IRole;
/**
* Indicates the hosting platform to use. Set to WEB for static site
* generated (SSG) apps (i.e. a Create React App or Gatsby) and WEB_COMPUTE
* for server side rendered (SSR) apps (i.e. NextJS).
*
* @default Platform.WEB
*/
readonly platform?: Platform;
/**
* The type of cache configuration to use for an Amplify app.
*
* @default CacheConfigType.AMPLIFY_MANAGED
*/
readonly cacheConfigType?: CacheConfigType;
}
/**
* An Amplify Console application
*/
export class App extends Resource implements IApp, iam.IGrantable {
/**
* Import an existing application
*/
public static fromAppId(scope: Construct, id: string, appId: string): IApp {
class Import extends Resource implements IApp {
public readonly appId = appId;
}
return new Import(scope, id);
}
public readonly appId: string;
/**
* The name of the application
*
* @attribute
*/
public readonly appName: string;
/**
* The ARN of the application
*
* @attribute
*/
public readonly arn: string;
/**
* The default domain of the application
*
* @attribute
*/
public readonly defaultDomain: string;
/**
* The principal to grant permissions to
*/
public readonly grantPrincipal: iam.IPrincipal;
private readonly customRules: CustomRule[];
private readonly environmentVariables: { [name: string]: string };
private readonly autoBranchEnvironmentVariables: { [name: string]: string };
constructor(scope: Construct, id: string, props: AppProps) {
super(scope, id);
// Enhanced CDK Analytics Telemetry
addConstructMetadata(this, props);
this.customRules = props.customRules || [];
this.environmentVariables = props.environmentVariables || {};
this.autoBranchEnvironmentVariables = props.autoBranchCreation && props.autoBranchCreation.environmentVariables || {};
const role = props.role || new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('amplify.amazonaws.com'),
});
this.grantPrincipal = role;
const sourceCodeProviderOptions = props.sourceCodeProvider?.bind(this);
const app = new CfnApp(this, 'Resource', {
accessToken: sourceCodeProviderOptions?.accessToken?.unsafeUnwrap(), // Safe usage
autoBranchCreationConfig: props.autoBranchCreation && {
autoBranchCreationPatterns: props.autoBranchCreation.patterns,
basicAuthConfig: props.autoBranchCreation.basicAuth
? props.autoBranchCreation.basicAuth.bind(this, 'BranchBasicAuth')
: { enableBasicAuth: false },
buildSpec: props.autoBranchCreation.buildSpec && props.autoBranchCreation.buildSpec.toBuildSpec(),
enableAutoBranchCreation: true,
enableAutoBuild: props.autoBranchCreation.autoBuild ?? true,
environmentVariables: Lazy.any({ produce: () => renderEnvironmentVariables(this.autoBranchEnvironmentVariables) }, { omitEmptyArray: true }), // eslint-disable-line max-len
enablePullRequestPreview: props.autoBranchCreation.pullRequestPreview ?? true,
pullRequestEnvironmentName: props.autoBranchCreation.pullRequestEnvironmentName,
stage: props.autoBranchCreation.stage,
},
enableBranchAutoDeletion: props.autoBranchDeletion,
basicAuthConfig: props.basicAuth
? props.basicAuth.bind(this, 'AppBasicAuth')
: { enableBasicAuth: false },
buildSpec: props.buildSpec && props.buildSpec.toBuildSpec(),
cacheConfig: props.cacheConfigType ? { type: props.cacheConfigType } : undefined,
customRules: Lazy.any({ produce: () => this.customRules }, { omitEmptyArray: true }),
description: props.description,
environmentVariables: Lazy.any({ produce: () => renderEnvironmentVariables(this.environmentVariables) }, { omitEmptyArray: true }),
iamServiceRole: role.roleArn,
name: props.appName || this.node.id,
oauthToken: sourceCodeProviderOptions?.oauthToken?.unsafeUnwrap(), // Safe usage
repository: sourceCodeProviderOptions?.repository,
customHeaders: props.customResponseHeaders ? renderCustomResponseHeaders(props.customResponseHeaders) : undefined,
platform: props.platform || Platform.WEB,
});
this.appId = app.attrAppId;
this.appName = app.attrAppName;
this.arn = app.attrArn;
this.defaultDomain = app.attrDefaultDomain;
}
/**
* Adds a custom rewrite/redirect rule to this application
*/
@MethodMetadata()
public addCustomRule(rule: CustomRule) {
this.customRules.push(rule);
return this;
}
/**
* Adds an environment variable to this application.
*
* All environment variables that you add are encrypted to prevent rogue
* access so you can use them to store secret information.
*/
@MethodMetadata()
public addEnvironment(name: string, value: string) {
this.environmentVariables[name] = value;
return this;
}
/**
* Adds an environment variable to the auto created branch.
*
* All environment variables that you add are encrypted to prevent rogue
* access so you can use them to store secret information.
*/
@MethodMetadata()
public addAutoBranchEnvironment(name: string, value: string) {
this.autoBranchEnvironmentVariables[name] = value;
return this;
}
/**
* Adds a branch to this application
*/
@MethodMetadata()
public addBranch(id: string, options: BranchOptions = {}): Branch {
return new Branch(this, id, {
...options,
app: this,
});
}
/**
* Adds a domain to this application
*/
@MethodMetadata()
public addDomain(id: string, options: DomainOptions = {}): Domain {
return new Domain(this, id, {
...options,
app: this,
autoSubDomainIamRole: this.grantPrincipal as iam.IRole,
});
}
}
/**
* Auto branch creation configuration
*/
export interface AutoBranchCreation {
/**
* Automated branch creation glob patterns
*
* @default - all repository branches
*/
readonly patterns?: string[];
/**
* The Basic Auth configuration. Use this to set password protection for
* the auto created branch.
*
* @default - no password protection
*/
readonly basicAuth?: BasicAuth;
/**
* Build spec for the auto created branch.
*
* @default - application build spec
*/
readonly buildSpec?: codebuild.BuildSpec;
/**
* Whether to enable auto building for the auto created branch
*
* @default true
*/
readonly autoBuild?: boolean;
/**
* Whether to enable pull request preview for the auto created branch.
*
* @default true
*/
readonly pullRequestPreview?: boolean;
/**
* Environment variables for the auto created branch.
*
* All environment variables that you add are encrypted to prevent rogue
* access so you can use them to store secret information.
*
* @default - application environment variables
*/
readonly environmentVariables?: { [name: string]: string };
/**
* The dedicated backend environment for the pull request previews of
* the auto created branch.
*
* @default - automatically provision a temporary backend
*/
readonly pullRequestEnvironmentName?: string;
/**
* Stage for the auto created branch
*
* @default - no stage
*/
readonly stage?: string;
}
/**
* The status code for a URL rewrite or redirect rule.
*/
export enum RedirectStatus {
/**
* Rewrite (200)
*/
REWRITE = '200',
/**
* Permanent redirect (301)
*/
PERMANENT_REDIRECT = '301',
/**
* Temporary redirect (302)
*/
TEMPORARY_REDIRECT = '302',
/**
* Not found (404)
*/
NOT_FOUND = '404',
/**
* Not found rewrite (404)
*/
NOT_FOUND_REWRITE = '404-200',
}
/**
* Options for a custom rewrite/redirect rule for an Amplify App.
*/
export interface CustomRuleOptions {
/**
* The source pattern for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*/
readonly source: string;
/**
* The target pattern for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*/
readonly target: string;
/**
* The status code for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*
* @default PERMANENT_REDIRECT
*/
readonly status?: RedirectStatus;
/**
* The condition for a URL rewrite or redirect rule, e.g. country code.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*
* @default - no condition
*/
readonly condition?: string;
}
/**
* Custom rewrite/redirect rule for an Amplify App.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*/
export class CustomRule {
/**
* Sets up a 200 rewrite for all paths to `index.html` except for path
* containing a file extension.
*/
public static readonly SINGLE_PAGE_APPLICATION_REDIRECT = new CustomRule({
source: '</^[^.]+$/>',
target: '/index.html',
status: RedirectStatus.REWRITE,
});
/**
* The source pattern for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*/
public readonly source: string;
/**
* The target pattern for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*/
public readonly target: string;
/**
* The status code for a URL rewrite or redirect rule.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*
* @default PERMANENT_REDIRECT
*/
public readonly status?: RedirectStatus;
/**
* The condition for a URL rewrite or redirect rule, e.g. country code.
*
* @see https://docs.aws.amazon.com/amplify/latest/userguide/redirects.html
*
* @default - no condition
*/
public readonly condition?: string;
constructor(options: CustomRuleOptions) {
this.source = options.source;
this.target = options.target;
this.status = options.status;
this.condition = options.condition;
}
}
/**
* Custom response header of an Amplify App.
*/
export interface CustomResponseHeader {
/**
* These custom headers will be applied to all URL file paths that match this pattern.
*/
readonly pattern: string;
/**
* The map of custom headers to be applied.
*/
readonly headers: { [key: string]: string };
}
function renderCustomResponseHeaders(customHeaders: CustomResponseHeader[]): string {
const yaml = [
'customHeaders:',
];
for (const customHeader of customHeaders) {
yaml.push(` - pattern: "${customHeader.pattern}"`);
yaml.push(' headers:');
for (const [key, value] of Object.entries(customHeader.headers)) {
yaml.push(` - key: "${key}"`);
yaml.push(` value: "${value}"`);
}
}
return `${yaml.join('\n')}\n`;
}
/**
* Available hosting platforms to use on the App.
*/
export enum Platform {
/**
* WEB - Used to indicate that the app is hosted using only static assets.
*/
WEB = 'WEB',
/**
* WEB_COMPUTE - Used to indicate the app is hosted using a combination of
* server side rendered and static assets.
*/
WEB_COMPUTE = 'WEB_COMPUTE',
/**
* WEB_DYNAMIC - Used to indicate the app is hosted using a fully dynamic architecture, where requests are processed at runtime by backend compute services.
*/
WEB_DYNAMIC = 'WEB_DYNAMIC',
}
/**
* The type of cache configuration to use for an Amplify app.
*/
export enum CacheConfigType {
/**
* AMPLIFY_MANAGED - Automatically applies an optimized cache configuration
* for your app based on its platform, routing rules, and rewrite rules.
*/
AMPLIFY_MANAGED = 'AMPLIFY_MANAGED',
/**
* AMPLIFY_MANAGED_NO_COOKIES - The same as AMPLIFY_MANAGED,
* except that it excludes all cookies from the cache key.
*/
AMPLIFY_MANAGED_NO_COOKIES = 'AMPLIFY_MANAGED_NO_COOKIES',
}