-
Notifications
You must be signed in to change notification settings - Fork 14
/
stack-api.ts
480 lines (438 loc) · 16.6 KB
/
stack-api.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
import * as cdk from 'aws-cdk-lib'
import * as path from 'path'
import { Construct } from 'constructs'
import { AuthorizationType, FieldLogLevel, GraphqlApi, MappingTemplate, Schema } from '@aws-cdk/aws-appsync-alpha'
import {
Role,
PolicyStatement,
ManagedPolicy,
FederatedPrincipal,
Effect,
} from 'aws-cdk-lib/aws-iam'
import { Stack, StackProps, CfnOutput } from 'aws-cdk-lib'
import {
AccountRecovery,
BooleanAttribute,
CfnUserPoolGroup,
CfnUserPoolUser,
CfnUserPoolUserToGroupAttachment,
DateTimeAttribute,
StringAttribute,
UserPool,
UserPoolClient,
VerificationEmailStyle,
CfnIdentityPoolRoleAttachment,
CfnIdentityPool,
AdvancedSecurityMode,
} from 'aws-cdk-lib/aws-cognito'
import {
IdentityPool,
RoleMappingMatchType,
} from '@aws-cdk/aws-cognito-identitypool-alpha'
import { NagSuppressions } from 'cdk-nag/lib/nag-suppressions'
export interface ApiStackProps extends StackProps {
calculatorOutputTableRef: cdk.aws_dynamodb.Table
adminEmail?: string
}
export class ApiStack extends Stack {
// API
public readonly graphqlUrl: string
public readonly apiId: string
// Cognito
// public readonly userPool: IUserPool;
public readonly userPool: UserPool
// public readonly identityPool: IIdentityPool;
public readonly identityPool: IdentityPool
// public readonly userPoolClient: IUserPoolClient;
public readonly userPoolClient: UserPoolClient
public readonly adminUser: CfnUserPoolUser
// IAM
public readonly cdlAdminUserRole: Role
public readonly cdlStandardUserRole: Role
public readonly cdlAuthRole: Role
public readonly cdlUnAuthRole: Role
public readonly cdlAdminUserRoleManagedPolicy: ManagedPolicy
public readonly clStandardUserRoleManagedPolicy: ManagedPolicy
public readonly cdlIdentityPool: CfnIdentityPool
// Outputs
public readonly userPoolClientIdOutput: CfnOutput
public readonly identityPoolIdOutputId: CfnOutput
public readonly userPoolIdOutput: CfnOutput
constructor(scope: Construct, id: string, props: ApiStackProps) {
super(scope, id, props)
const defaultAdminEmail = this.node.tryGetContext('adminEmail')
// -- COGNITO USER POOL --
const userPool = new UserPool(this, 'cdlUserPool', {
userPoolName: 'cdlUserPool',
signInAliases: {
email: true,
username: false,
},
removalPolicy: cdk.RemovalPolicy.DESTROY, // Set the user pool to be detroyed if the stack that deployed it is destroyed
selfSignUpEnabled: false, // Prevent users to sign up (security mechanism)
autoVerify: { email: true }, // Verify email addresses by sending a verification code
accountRecovery: AccountRecovery.EMAIL_ONLY, // Restricts account recovery only to email method
// Invite Message
passwordPolicy: {
minLength: 8,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: true
},
advancedSecurityMode: AdvancedSecurityMode.ENFORCED,
userInvitation: {
emailSubject: `Welcome to AWS Carbon Data Lake!`,
emailBody:
'Hello {username}, you have been invited to join the AWS Carbon Data Lake app! Your temporary password is {####}',
smsMessage: 'Hello {username}, your temporary password for the AWS Carbon Data Lake app is {####}',
},
// Verification Message
userVerification: {
emailSubject: 'Verify your email for AWS Carbon Data Lake',
emailBody: 'Thanks for signing up for AWS Carbon Data Lake! Your verification code is {####}',
emailStyle: VerificationEmailStyle.CODE,
smsMessage: 'Thanks for signing up for AWS Carbon Data Lake! Your verification code is {####}',
},
// Standard User Attributes
standardAttributes: {
email: {
required: true,
mutable: false,
},
givenName: {
required: true,
mutable: true,
},
familyName: {
required: true,
mutable: true,
},
},
customAttributes: {
joinedOn: new DateTimeAttribute(),
isAdmin: new BooleanAttribute({ mutable: false }),
myappid: new StringAttribute({ minLen: 5, maxLen: 15, mutable: false }),
},
})
NagSuppressions.addResourceSuppressions(userPool, [
{
id: 'AwsSolutions-COG2',
reason: 'Not requiring MFA by default because this is a development tool. Users are encouraged to enabled in all production environments.'
},
])
// -- COGNITO USER POOL (APP) CLIENT
const userPoolClient = new UserPoolClient(this, 'cdlUserPoolClient', {
userPool: userPool,
userPoolClientName: 'cdlUserPoolClient',
generateSecret: false, // Don't need to generate secret for web app running on browsers
})
// // -- COGNITO IDENTITY POOL
// const identityPool = new IdentityPool(this, 'cdlIdentityPool', {
// identityPoolName: 'cdlIdentityPool',
// // allowUnauthenticatedIdentities: true,
// allowUnauthenticatedIdentities: false,
// cognitoIdentityProviders: [
// {
// clientId: userPoolClient.userPoolClientId,
// providerName: userPool.userPoolProviderName,
// },
// ],
// });
// -- COGNITO IDENTITY POOL
this.cdlIdentityPool = new CfnIdentityPool(this, 'cdlIdentityPool', {
identityPoolName: 'cdlIdentityPool',
allowUnauthenticatedIdentities: false,
cognitoIdentityProviders: [
{
clientId: userPoolClient.userPoolClientId,
providerName: userPool.userPoolProviderName,
},
],
})
// --- IAM ---
// -- AuthRole --
// Create cdlAuthRole IAM Role using the custom managed policy
this.cdlAuthRole = new Role(this, 'cdlAuthRole', {
assumedBy: new FederatedPrincipal(
'cognito-identity.amazonaws.com',
{
StringEquals: {
'cognito-identity.amazonaws.com:aud': this.cdlIdentityPool.ref,
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'authenticated',
},
},
'sts:AssumeRoleWithWebIdentity'
),
managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName('AmazonS3ReadOnlyAccess')],
description: 'cdlAuthRole granting read-only access to S3',
})
// -- cdlUnAuthRole --
// Create cdlUnAuthRole IAM Role using the custom managed policy
this.cdlUnAuthRole = new Role(this, 'cdlUnAuthRole', {
assumedBy: new FederatedPrincipal(
'cognito-identity.amazonaws.com',
{
StringEquals: {
'cognito-identity.amazonaws.com:aud': this.cdlIdentityPool.ref,
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'unauthenticated',
},
},
'sts:AssumeRoleWithWebIdentity'
),
managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName('AmazonS3ReadOnlyAccess')],
description: 'cdlUnAuthRole granting access to S3',
})
// -- cdlAdminUserRole --
// Create cdlAdminUserRole IAM Role using the custom managed policy
const cdlAdminUserRole = new Role(this, 'cdlAdminUserRole', {
assumedBy: new FederatedPrincipal(
'cognito-identity.amazonaws.com',
{
StringEquals: {
'cognito-identity.amazonaws.com:aud': this.cdlIdentityPool.ref,
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'authenticated',
},
},
'sts:AssumeRoleWithWebIdentity'
),
// managedPolicies: [
// iam.ManagedPolicy.fromManagedPolicyName(scAdminS3PolicyDocument)
// ],
description: 'cdlAdminUserRole granting access to S3',
})
this.cdlAdminUserRoleManagedPolicy = new ManagedPolicy(this, 'cdlAdminUserRoleManagedPolicy', {
description: 'All permissions for cdlAdminUserRole',
statements: [
new PolicyStatement({
effect: Effect.ALLOW,
actions: ['s3:*'],
resources: ['*'],
}),
],
roles: [cdlAdminUserRole],
})
// // -- cdlStandardUserRole --
// // Create cdlStandardUserRole IAM Role using the custom managed policy
this.cdlStandardUserRole = new Role(this, 'cdlStandardUserRole', {
assumedBy: new FederatedPrincipal(
'cognito-identity.amazonaws.com',
{
StringEquals: {
'cognito-identity.amazonaws.com:aud': this.cdlIdentityPool.ref,
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'authenticated',
},
},
'sts:AssumeRoleWithWebIdentity'
),
// managedPolicies: [
// iam.ManagedPolicy.fromManagedPolicyName(scAdminS3PolicyDocument)
// ],
description: 'cdlStandardUserRole granting access to S3',
})
this.clStandardUserRoleManagedPolicy = new ManagedPolicy(this, 'cdlStandardUserRoleManagedPolicy', {
description: 'All permissions for cdlStandardUserRole',
statements: [
new PolicyStatement({
effect: Effect.ALLOW,
actions: ['s3:getObject'],
resources: ['*'],
}),
],
roles: [this.cdlStandardUserRole],
})
// -- IDENTITY POOL ROLE ATTACHMENT --
const cdlRegion = cdk.Stack.of(this).region // Reference current AWS Region
const identityProviderUrl = `cognito-idp.${cdlRegion}.amazonaws.com/${userPool.userPoolId}:${userPoolClient.userPoolClientId}`
new CfnIdentityPoolRoleAttachment(this, 'identity-pool-role-attachment', {
identityPoolId: this.cdlIdentityPool.ref,
roles: {
authenticated: this.cdlAuthRole.roleArn,
unauthenticated: this.cdlUnAuthRole.roleArn,
},
roleMappings: {
roleMappingsKey: {
type: 'Rules',
ambiguousRoleResolution: 'Deny',
identityProvider: identityProviderUrl,
rulesConfiguration: {
rules: [
{
claim: 'cognito:groups',
matchType: RoleMappingMatchType.CONTAINS,
roleArn: cdlAdminUserRole.roleArn,
value: 'Admin',
},
{
claim: 'cognito:groups',
matchType: RoleMappingMatchType.CONTAINS,
roleArn: this.cdlStandardUserRole.roleArn,
value: 'Standard-Users',
},
],
},
},
},
})
// -- COGNITO USER POOL GROUPS
const cdlAdminUserPoolGroup = new CfnUserPoolGroup(this, 'cdlAdmin', {
userPoolId: userPool.userPoolId,
description: 'Admin user group',
groupName: 'Admin',
precedence: 1,
roleArn: cdlAdminUserRole.roleArn,
})
cdlAdminUserPoolGroup.node.addDependency(cdlAdminUserRole)
const cdlStandardUserPoolGroup = new CfnUserPoolGroup(this, 'cdlStandard', {
userPoolId: userPool.userPoolId,
groupName: 'Standard-Users',
description: 'Standard user group',
precedence: 2,
roleArn: this.cdlStandardUserRole.roleArn,
})
// Create an initial admin user with the email address provided in the CDK context
const adminUser = new CfnUserPoolUser(this, 'cdlDefaultAdminUser', {
userPoolId: userPool.userPoolId,
desiredDeliveryMediums: ['EMAIL'],
userAttributes: [
{
name: 'email',
value: props.adminEmail,
},
{
name: 'given_name',
value: 'Carbon Data Lake',
},
{
name: 'family_name',
value: 'Admin',
},
],
username: props.adminEmail,
})
const cfnUserPoolUserToGroupAttachment = new CfnUserPoolUserToGroupAttachment(
this,
'MyCfnUserPoolUserToGroupAttachment',
{
groupName: 'Admin',
username: defaultAdminEmail,
userPoolId: userPool.userPoolId,
}
)
// Prevent creation of UserGroupAttachment until User is created
cfnUserPoolUserToGroupAttachment.node.addDependency(adminUser)
cfnUserPoolUserToGroupAttachment.node.addDependency(cdlAdminUserPoolGroup)
// Create the GraphQL api and provide the schema.graphql file
const api = new GraphqlApi(this, 'cdlApi', {
name: 'cdlApi',
schema: Schema.fromAsset(path.join(__dirname, 'schema.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: AuthorizationType.USER_POOL,
userPoolConfig: {
userPool: userPool,
},
},
},
logConfig: {
excludeVerboseContent: true,
fieldLogLevel: FieldLogLevel.ALL,
},
xrayEnabled: true
})
NagSuppressions.addResourceSuppressions(api, [{
id: 'AwsSolutions-ASC3',
reason: 'Request level access logging disabled for sample code.'
}])
// Set the public variables so other stacks can access the deployed graphqlUrl & apiId as well as set as CloudFormation output variables
this.graphqlUrl = api.graphqlUrl
new CfnOutput(this, 'graphqlUrl', { value: api.graphqlUrl })
this.apiId = api.apiId
new CfnOutput(this, 'apiId', { value: api.apiId })
// Add a DynamoDB datasource. The DynamoDB table we will use is created by another stack
// and is provided in the props of this stack.
const datasource = api.addDynamoDbDataSource('CalculatorOutputDataSource', props.calculatorOutputTableRef, {
name: 'CalculatorOutputDataSource',
})
// Create a resolver for getting 1 record by the activity_event_id
datasource.createResolver({
typeName: 'Query',
fieldName: 'getOne',
requestMappingTemplate: MappingTemplate.dynamoDbGetItem('activity_event_id', 'activity_event_id'),
responseMappingTemplate: MappingTemplate.dynamoDbResultItem(),
})
// Create a resolver for getting a list of records. This resolver will limit the number of records
// returned by a value provided or by a default of 20. This resolver can be used for pagination.
datasource.createResolver({
typeName: 'Query',
fieldName: 'all',
requestMappingTemplate: MappingTemplate.fromString(`{
"version": "2018-05-29",
"operation": "Scan",
"limit": $util.defaultIfNull($ctx.args.limit, 20),
"nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null))
}`),
responseMappingTemplate: MappingTemplate.dynamoDbResultItem(),
})
// Create a resolver for deleting a record by the activity_event_id
// Commented out. Uncomment if you wish to use.
//datasource.createResolver({
//typeName: 'Mutation',
//fieldName: 'delete',
//requestMappingTemplate: MappingTemplate.dynamoDbDeleteItem('activity_event_id', 'activity_event_id'),
//responseMappingTemplate: MappingTemplate.dynamoDbResultItem(),
//})
// -- Outputs --
// Set the public variables so other stacks can access the deployed auth/auz related stuff above as well as set as CloudFormation output variables
// Cognito
this.userPoolIdOutput = new CfnOutput(this, 'cdluserPoolId', {
value: userPool.userPoolId,
exportName: 'cdluserPoolId'
})
this.identityPoolIdOutputId = new CfnOutput(this, 'identityPoolId', {
value: this.cdlIdentityPool.ref,
exportName: 'CLQidentityPoolId'
})
this.userPoolClientIdOutput = new CfnOutput(this, 'userPoolClientId', {
value: userPoolClient.userPoolClientId,
exportName: 'cdluserPoolClientId'
})
// IAM
this.cdlAdminUserRole = cdlAdminUserRole
new CfnOutput(this, 'cdlAdminUserRoleOutput', {
value: this.cdlAdminUserRole.roleArn,
exportName: 'cdlcdlAdminUserRoleOutput'
})
new CfnOutput(this, 'cdlStandardUserRoleOutput', {
value: this.cdlStandardUserRole.roleArn,
exportName: 'cdlcdlStandardUserRoleOutput'
})
// Output API Endpoint
new cdk.CfnOutput(this, 'apiEndpoint', {
value: this.graphqlUrl,
description: 'Base http endpoint for CarbonLake Quickstart GraphQL API',
exportName: 'cdlApiEndpoint',
});
// Output API Username (password will be email to admin user on create)
new cdk.CfnOutput(this, 'adminUsername', {
value: adminUser.username ?? '' ,
description: 'Admin username created on build for GraphQL API',
exportName: 'cdlApiUsername',
});
// Output Appsync Query Link
new cdk.CfnOutput(this, 'graphqueryTestUrl', {
value: `https://${this.region}.console.aws.amazon.com/appsync/home?region=${this.region}#/${this.apiId}/v1/queries`,
description: 'URL for testing AppSync GraphQL API queries in the AWS console.',
exportName: 'cdlGraphQLTestQueryURL',
});
cdk.Tags.of(this).add("component", "graphQLApi");
}
}