-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
graphqlapi.ts
591 lines (541 loc) · 16.5 KB
/
graphqlapi.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
import { IUserPool } from '@aws-cdk/aws-cognito';
import { ManagedPolicy, Role, ServicePrincipal, Grant, IGrantable } from '@aws-cdk/aws-iam';
import { CfnResource, Construct, Duration, IResolvable, Stack } from '@aws-cdk/core';
import { CfnApiKey, CfnGraphQLApi, CfnGraphQLSchema } from './appsync.generated';
import { IGraphqlApi, GraphqlApiBase } from './graphqlapi-base';
import { Schema } from './schema';
import { IIntermediateType } from './schema-base';
/**
* enum with all possible values for AppSync authorization type
*/
export enum AuthorizationType {
/**
* API Key authorization type
*/
API_KEY = 'API_KEY',
/**
* AWS IAM authorization type. Can be used with Cognito Identity Pool federated credentials
*/
IAM = 'AWS_IAM',
/**
* Cognito User Pool authorization type
*/
USER_POOL = 'AMAZON_COGNITO_USER_POOLS',
/**
* OpenID Connect authorization type
*/
OIDC = 'OPENID_CONNECT',
}
/**
* Interface to specify default or additional authorization(s)
*/
export interface AuthorizationMode {
/**
* One of possible four values AppSync supports
*
* @see https://docs.aws.amazon.com/appsync/latest/devguide/security.html
*
* @default - `AuthorizationType.API_KEY`
*/
readonly authorizationType: AuthorizationType;
/**
* If authorizationType is `AuthorizationType.USER_POOL`, this option is required.
* @default - none
*/
readonly userPoolConfig?: UserPoolConfig;
/**
* If authorizationType is `AuthorizationType.API_KEY`, this option can be configured.
* @default - name: 'DefaultAPIKey' | description: 'Default API Key created by CDK'
*/
readonly apiKeyConfig?: ApiKeyConfig;
/**
* If authorizationType is `AuthorizationType.OIDC`, this option is required.
* @default - none
*/
readonly openIdConnectConfig?: OpenIdConnectConfig;
}
/**
* enum with all possible values for Cognito user-pool default actions
*/
export enum UserPoolDefaultAction {
/**
* ALLOW access to API
*/
ALLOW = 'ALLOW',
/**
* DENY access to API
*/
DENY = 'DENY',
}
/**
* Configuration for Cognito user-pools in AppSync
*/
export interface UserPoolConfig {
/**
* The Cognito user pool to use as identity source
*/
readonly userPool: IUserPool;
/**
* the optional app id regex
*
* @default - None
*/
readonly appIdClientRegex?: string;
/**
* Default auth action
*
* @default ALLOW
*/
readonly defaultAction?: UserPoolDefaultAction;
}
/**
* Configuration for API Key authorization in AppSync
*/
export interface ApiKeyConfig {
/**
* Unique name of the API Key
* @default - 'DefaultAPIKey'
*/
readonly name?: string;
/**
* Description of API key
* @default - 'Default API Key created by CDK'
*/
readonly description?: string;
/**
* The time from creation time after which the API key expires, using RFC3339 representation.
* It must be a minimum of 1 day and a maximum of 365 days from date of creation.
* Rounded down to the nearest hour.
* @default - 7 days from creation time
*/
readonly expires?: string;
}
/**
* Configuration for OpenID Connect authorization in AppSync
*/
export interface OpenIdConnectConfig {
/**
* The number of milliseconds an OIDC token is valid after being authenticated by OIDC provider.
* `auth_time` claim in OIDC token is required for this validation to work.
* @default - no validation
*/
readonly tokenExpiryFromAuth?: number;
/**
* The number of milliseconds an OIDC token is valid after being issued to a user.
* This validation uses `iat` claim of OIDC token.
* @default - no validation
*/
readonly tokenExpiryFromIssue?: number;
/**
* The client identifier of the Relying party at the OpenID identity provider.
* A regular expression can be specified so AppSync can validate against multiple client identifiers at a time.
* @example - 'ABCD|CDEF' where ABCD and CDEF are two different clientId
* @default - * (All)
*/
readonly clientId?: string;
/**
* The issuer for the OIDC configuration. The issuer returned by discovery must exactly match the value of `iss` in the OIDC token.
*/
readonly oidcProvider: string;
}
/**
* Configuration of the API authorization modes.
*/
export interface AuthorizationConfig {
/**
* Optional authorization configuration
*
* @default - API Key authorization
*/
readonly defaultAuthorization?: AuthorizationMode;
/**
* Additional authorization modes
*
* @default - No other modes
*/
readonly additionalAuthorizationModes?: AuthorizationMode[];
}
/**
* log-level for fields in AppSync
*/
export enum FieldLogLevel {
/**
* No logging
*/
NONE = 'NONE',
/**
* Error logging
*/
ERROR = 'ERROR',
/**
* All logging
*/
ALL = 'ALL',
}
/**
* Logging configuration for AppSync
*/
export interface LogConfig {
/**
* exclude verbose content
*
* @default false
*/
readonly excludeVerboseContent?: boolean | IResolvable;
/**
* log level for fields
*
* @default - Use AppSync default
*/
readonly fieldLogLevel?: FieldLogLevel;
}
/**
* Properties for an AppSync GraphQL API
*/
export interface GraphQLApiProps {
/**
* the name of the GraphQL API
*/
readonly name: string;
/**
* Optional authorization configuration
*
* @default - API Key authorization
*/
readonly authorizationConfig?: AuthorizationConfig;
/**
* Logging configuration for this api
*
* @default - None
*/
readonly logConfig?: LogConfig;
/**
* GraphQL schema definition. Specify how you want to define your schema.
*
* Schema.fromFile(filePath: string) allows schema definition through schema.graphql file
*
* @default - schema will be generated code-first (i.e. addType, addObjectType, etc.)
*
* @experimental
*/
readonly schema?: Schema;
/**
* A flag indicating whether or not X-Ray tracing is enabled for the GraphQL API.
*
* @default - false
*/
readonly xrayEnabled?: boolean;
}
/**
* A class used to generate resource arns for AppSync
*/
export class IamResource {
/**
* Generate the resource names given custom arns
*
* @param arns The custom arns that need to be permissioned
*
* Example: custom('/types/Query/fields/getExample')
*/
public static custom(...arns: string[]): IamResource {
if (arns.length === 0) {
throw new Error('At least 1 custom ARN must be provided.');
}
return new IamResource(arns);
}
/**
* Generate the resource names given a type and fields
*
* @param type The type that needs to be allowed
* @param fields The fields that need to be allowed, if empty grant permissions to ALL fields
*
* Example: ofType('Query', 'GetExample')
*/
public static ofType(type: string, ...fields: string[]): IamResource {
const arns = fields.length ? fields.map((field) => `types/${type}/fields/${field}`) : [`types/${type}/*`];
return new IamResource(arns);
}
/**
* Generate the resource names that accepts all types: `*`
*/
public static all(): IamResource {
return new IamResource(['*']);
}
private arns: string[];
private constructor(arns: string[]) {
this.arns = arns;
}
/**
* Return the Resource ARN
*
* @param api The GraphQL API to give permissions
*/
public resourceArns(api: GraphQLApi): string[] {
return this.arns.map((arn) => Stack.of(api).formatArn({
service: 'appsync',
resource: `apis/${api.apiId}`,
sep: '/',
resourceName: `${arn}`,
}));
}
}
/**
* Attributes for GraphQL imports
*/
export interface GraphqlApiAttributes {
/**
* an unique AWS AppSync GraphQL API identifier
* i.e. 'lxz775lwdrgcndgz3nurvac7oa'
*/
readonly graphqlApiId: string,
/**
* the arn for the GraphQL Api
* @default - autogenerated arn
*/
readonly graphqlApiArn?: string,
}
/**
* An AppSync GraphQL API
*
* @resource AWS::AppSync::GraphQLApi
*/
export class GraphQLApi extends GraphqlApiBase {
/**
* Import a GraphQL API through this function
*
* @param scope scope
* @param id id
* @param attrs GraphQL API Attributes of an API
*/
public static fromGraphqlApiAttributes(scope: Construct, id: string, attrs: GraphqlApiAttributes): IGraphqlApi {
const arn = attrs.graphqlApiArn ?? Stack.of(scope).formatArn({
service: 'appsync',
resource: `apis/${attrs.graphqlApiId}`,
});
class Import extends GraphqlApiBase {
public readonly apiId = attrs.graphqlApiId;
public readonly arn = arn;
constructor (s: Construct, i: string) {
super(s, i);
}
}
return new Import(scope, id);
}
/**
* an unique AWS AppSync GraphQL API identifier
* i.e. 'lxz775lwdrgcndgz3nurvac7oa'
*/
public readonly apiId: string;
/**
* the ARN of the API
*/
public readonly arn: string;
/**
* the URL of the endpoint created by AppSync
*
* @attribute
*/
public readonly graphQlUrl: string;
/**
* the name of the API
*/
public readonly name: string;
/**
* the schema attached to this api
*/
public readonly schema: Schema;
/**
* the configured API key, if present
*
* @default - no api key
*/
public readonly apiKey?: string;
private schemaResource: CfnGraphQLSchema;
private api: CfnGraphQLApi;
private apiKeyResource?: CfnApiKey;
constructor(scope: Construct, id: string, props: GraphQLApiProps) {
super(scope, id);
const defaultMode = props.authorizationConfig?.defaultAuthorization ??
{ authorizationType: AuthorizationType.API_KEY };
const additionalModes = props.authorizationConfig?.additionalAuthorizationModes ?? [];
const modes = [defaultMode, ...additionalModes];
this.validateAuthorizationProps(modes);
this.api = new CfnGraphQLApi(this, 'Resource', {
name: props.name,
authenticationType: defaultMode.authorizationType,
logConfig: this.setupLogConfig(props.logConfig),
openIdConnectConfig: this.setupOpenIdConnectConfig(defaultMode.openIdConnectConfig),
userPoolConfig: this.setupUserPoolConfig(defaultMode.userPoolConfig),
additionalAuthenticationProviders: this.setupAdditionalAuthorizationModes(additionalModes),
xrayEnabled: props.xrayEnabled,
});
this.apiId = this.api.attrApiId;
this.arn = this.api.attrArn;
this.graphQlUrl = this.api.attrGraphQlUrl;
this.name = this.api.name;
this.schema = props.schema ?? new Schema();
this.schemaResource = this.schema.bind(this);
if (modes.some((mode) => mode.authorizationType === AuthorizationType.API_KEY)) {
const config = modes.find((mode: AuthorizationMode) => {
return mode.authorizationType === AuthorizationType.API_KEY && mode.apiKeyConfig;
})?.apiKeyConfig;
this.apiKeyResource = this.createAPIKey(config);
this.apiKeyResource.addDependsOn(this.schemaResource);
this.apiKey = this.apiKeyResource.attrApiKey;
}
}
/**
* Adds an IAM policy statement associated with this GraphQLApi to an IAM
* principal's policy.
*
* @param grantee The principal
* @param resources The set of resources to allow (i.e. ...:[region]:[accountId]:apis/GraphQLId/...)
* @param actions The actions that should be granted to the principal (i.e. appsync:graphql )
*/
public grant(grantee: IGrantable, resources: IamResource, ...actions: string[]): Grant {
return Grant.addToPrincipal({
grantee,
actions,
resourceArns: resources.resourceArns(this),
scope: this,
});
}
/**
* Adds an IAM policy statement for Mutation access to this GraphQLApi to an IAM
* principal's policy.
*
* @param grantee The principal
* @param fields The fields to grant access to that are Mutations (leave blank for all)
*/
public grantMutation(grantee: IGrantable, ...fields: string[]): Grant {
return this.grant(grantee, IamResource.ofType('Mutation', ...fields), 'appsync:GraphQL');
}
/**
* Adds an IAM policy statement for Query access to this GraphQLApi to an IAM
* principal's policy.
*
* @param grantee The principal
* @param fields The fields to grant access to that are Queries (leave blank for all)
*/
public grantQuery(grantee: IGrantable, ...fields: string[]): Grant {
return this.grant(grantee, IamResource.ofType('Query', ...fields), 'appsync:GraphQL');
}
/**
* Adds an IAM policy statement for Subscription access to this GraphQLApi to an IAM
* principal's policy.
*
* @param grantee The principal
* @param fields The fields to grant access to that are Subscriptions (leave blank for all)
*/
public grantSubscription(grantee: IGrantable, ...fields: string[]): Grant {
return this.grant(grantee, IamResource.ofType('Subscription', ...fields), 'appsync:GraphQL');
}
private validateAuthorizationProps(modes: AuthorizationMode[]) {
modes.map((mode) => {
if (mode.authorizationType === AuthorizationType.OIDC && !mode.openIdConnectConfig) {
throw new Error('Missing default OIDC Configuration');
}
if (mode.authorizationType === AuthorizationType.USER_POOL && !mode.userPoolConfig) {
throw new Error('Missing default OIDC Configuration');
}
});
if (modes.filter((mode) => mode.authorizationType === AuthorizationType.API_KEY).length > 1) {
throw new Error('You can\'t duplicate API_KEY configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html');
}
if (modes.filter((mode) => mode.authorizationType === AuthorizationType.IAM).length > 1) {
throw new Error('You can\'t duplicate IAM configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html');
}
}
/**
* Add schema dependency to a given construct
*
* @param construct the dependee
*/
public addSchemaDependency(construct: CfnResource): boolean {
construct.addDependsOn(this.schemaResource);
return true;
}
private setupLogConfig(config?: LogConfig) {
if (!config) return undefined;
const role = new Role(this, 'ApiLogsRole', {
assumedBy: new ServicePrincipal('appsync.amazonaws.com'),
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName(
'service-role/AWSAppSyncPushToCloudWatchLogs'),
],
});
return {
cloudWatchLogsRoleArn: role.roleArn,
excludeVerboseContent: config.excludeVerboseContent,
fieldLogLevel: config.fieldLogLevel,
};
}
private setupOpenIdConnectConfig(config?: OpenIdConnectConfig) {
if (!config) return undefined;
return {
authTtl: config.tokenExpiryFromAuth,
clientId: config.clientId,
iatTtl: config.tokenExpiryFromIssue,
issuer: config.oidcProvider,
};
}
private setupUserPoolConfig(config?: UserPoolConfig) {
if (!config) return undefined;
return {
userPoolId: config.userPool.userPoolId,
awsRegion: config.userPool.stack.region,
appIdClientRegex: config.appIdClientRegex,
defaultAction: config.defaultAction,
};
}
private setupAdditionalAuthorizationModes(modes?: AuthorizationMode[]) {
if (!modes || modes.length === 0) return undefined;
return modes.reduce<CfnGraphQLApi.AdditionalAuthenticationProviderProperty[]>((acc, mode) => [
...acc, {
authenticationType: mode.authorizationType,
userPoolConfig: this.setupUserPoolConfig(mode.userPoolConfig),
openIdConnectConfig: this.setupOpenIdConnectConfig(mode.openIdConnectConfig),
},
], []);
}
private createAPIKey(config?: ApiKeyConfig) {
let expires: number | undefined;
if (config?.expires) {
expires = new Date(config.expires).valueOf();
const days = (d: number) =>
Date.now() + Duration.days(d).toMilliseconds();
if (expires < days(1) || expires > days(365)) {
throw Error('API key expiration must be between 1 and 365 days.');
}
expires = Math.round(expires / 1000);
}
return new CfnApiKey(this, `${config?.name || 'Default'}ApiKey`, {
expires,
description: config?.description,
apiId: this.apiId,
});
}
/**
* Escape hatch to append to Schema as desired. Will always result
* in a newline.
*
* @param addition the addition to add to schema
* @param delimiter the delimiter between schema and addition
* @default - ''
*
* @experimental
*/
public addToSchema(addition: string, delimiter?: string): void {
this.schema.addToSchema(addition, delimiter);
}
/**
* Add type to the schema
*
* @param type the intermediate type to add to the schema
*
* @experimental
*/
public addType(type: IIntermediateType): IIntermediateType {
return this.schema.addType(type);
}
}