1 | "use strict";
|
2 | var __importStar = (this && this.__importStar) || function (mod) {
|
3 | if (mod && mod.__esModule) return mod;
|
4 | var result = {};
|
5 | if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
6 | result["default"] = mod;
|
7 | return result;
|
8 | };
|
9 | Object.defineProperty(exports, "__esModule", { value: true });
|
10 | const cloudform_types_1 = require("cloudform-types");
|
11 | const graphql_mapping_template_1 = require("graphql-mapping-template");
|
12 | const graphql_transformer_common_1 = require("graphql-transformer-common");
|
13 | const graphQlApi_1 = __importStar(require("cloudform-types/types/appSync/graphQlApi"));
|
14 | const constants_1 = require("./constants");
|
15 | function replaceIfUsername(identityClaim) {
|
16 | return identityClaim === 'username' ? 'cognito:username' : identityClaim;
|
17 | }
|
18 | function isUsername(identityClaim) {
|
19 | return identityClaim === 'username';
|
20 | }
|
21 | class ResourceFactory {
|
22 | constructor() {
|
23 | this.getSourceMapper = (includeVersion) => {
|
24 | if (includeVersion) {
|
25 | return [
|
26 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('row'), graphql_mapping_template_1.methodCall(graphql_mapping_template_1.ref('entry.get'), graphql_mapping_template_1.str('_source'))),
|
27 | graphql_mapping_template_1.qref('$row.put("_version", $entry.get("_version"))'),
|
28 | graphql_mapping_template_1.qref('$es_items.add($row)'),
|
29 | ];
|
30 | }
|
31 | return [graphql_mapping_template_1.qref('$es_items.add($entry.get("_source"))')];
|
32 | };
|
33 | }
|
34 | makeParams() {
|
35 | return {
|
36 | [graphql_transformer_common_1.ResourceConstants.PARAMETERS.AppSyncApiName]: new cloudform_types_1.StringParameter({
|
37 | Description: 'The name of the AppSync API',
|
38 | Default: 'AppSyncSimpleTransform',
|
39 | }),
|
40 | [graphql_transformer_common_1.ResourceConstants.PARAMETERS.APIKeyExpirationEpoch]: new cloudform_types_1.NumberParameter({
|
41 | Description: 'The epoch time in seconds when the API Key should expire.' +
|
42 | ' Setting this to 0 will default to 7 days from the deployment date.' +
|
43 | ' Setting this to -1 will not create an API Key.',
|
44 | Default: 0,
|
45 | MinValue: -1,
|
46 | }),
|
47 | [graphql_transformer_common_1.ResourceConstants.PARAMETERS.CreateAPIKey]: new cloudform_types_1.NumberParameter({
|
48 | Description: 'The boolean value to control if an API Key will be created or not.' +
|
49 | ' The value of the property is automatically set by the CLI.' +
|
50 | ' If the value is set to 0 no API Key will be created.',
|
51 | Default: 0,
|
52 | MinValue: 0,
|
53 | MaxValue: 1,
|
54 | }),
|
55 | [graphql_transformer_common_1.ResourceConstants.PARAMETERS.AuthCognitoUserPoolId]: new cloudform_types_1.StringParameter({
|
56 | Description: 'The id of an existing User Pool to connect. If this is changed, a user pool will not be created for you.',
|
57 | Default: graphql_transformer_common_1.ResourceConstants.NONE,
|
58 | }),
|
59 | };
|
60 | }
|
61 | initTemplate(apiKeyConfig) {
|
62 | return {
|
63 | Parameters: this.makeParams(),
|
64 | Resources: {
|
65 | [graphql_transformer_common_1.ResourceConstants.RESOURCES.APIKeyLogicalID]: this.makeAppSyncApiKey(apiKeyConfig),
|
66 | },
|
67 | Outputs: {
|
68 | [graphql_transformer_common_1.ResourceConstants.OUTPUTS.GraphQLAPIApiKeyOutput]: this.makeApiKeyOutput(),
|
69 | },
|
70 | Conditions: {
|
71 | [graphql_transformer_common_1.ResourceConstants.CONDITIONS.ShouldCreateAPIKey]: cloudform_types_1.Fn.Equals(cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.CreateAPIKey), 1),
|
72 | [graphql_transformer_common_1.ResourceConstants.CONDITIONS.APIKeyExpirationEpochIsPositive]: cloudform_types_1.Fn.And([
|
73 | cloudform_types_1.Fn.Not(cloudform_types_1.Fn.Equals(cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.APIKeyExpirationEpoch), -1)),
|
74 | cloudform_types_1.Fn.Not(cloudform_types_1.Fn.Equals(cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.APIKeyExpirationEpoch), 0)),
|
75 | ]),
|
76 | },
|
77 | };
|
78 | }
|
79 | makeAppSyncApiKey(apiKeyConfig) {
|
80 | let expirationDays = 7;
|
81 | if (apiKeyConfig && apiKeyConfig.apiKeyExpirationDays) {
|
82 | expirationDays = apiKeyConfig.apiKeyExpirationDays;
|
83 | }
|
84 | const expirationDateInSeconds = 60 * 60 * 24 * expirationDays;
|
85 | const nowEpochTime = Math.floor(Date.now() / 1000);
|
86 | return new cloudform_types_1.AppSync.ApiKey({
|
87 | ApiId: cloudform_types_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
|
88 | Description: apiKeyConfig && apiKeyConfig.description ? apiKeyConfig.description : undefined,
|
89 | Expires: cloudform_types_1.Fn.If(graphql_transformer_common_1.ResourceConstants.CONDITIONS.APIKeyExpirationEpochIsPositive, cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.APIKeyExpirationEpoch), nowEpochTime + expirationDateInSeconds),
|
90 | }).condition(graphql_transformer_common_1.ResourceConstants.CONDITIONS.ShouldCreateAPIKey);
|
91 | }
|
92 | makeApiKeyOutput() {
|
93 | return {
|
94 | Description: "Your GraphQL API key. Provide via 'x-api-key' header.",
|
95 | Value: cloudform_types_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.APIKeyLogicalID, 'ApiKey'),
|
96 | Export: {
|
97 | Name: cloudform_types_1.Fn.Join(':', [cloudform_types_1.Refs.StackName, 'GraphQLApiKey']),
|
98 | },
|
99 | Condition: graphql_transformer_common_1.ResourceConstants.CONDITIONS.ShouldCreateAPIKey,
|
100 | };
|
101 | }
|
102 | updateGraphQLAPIWithAuth(apiRecord, authConfig) {
|
103 | let properties = {
|
104 | ...apiRecord.Properties,
|
105 | Name: apiRecord.Properties.Name,
|
106 | AuthenticationType: authConfig.defaultAuthentication.authenticationType,
|
107 | UserPoolConfig: undefined,
|
108 | OpenIDConnectConfig: undefined,
|
109 | };
|
110 | switch (authConfig.defaultAuthentication.authenticationType) {
|
111 | case 'AMAZON_COGNITO_USER_POOLS':
|
112 | properties.UserPoolConfig = new graphQlApi_1.UserPoolConfig({
|
113 | UserPoolId: cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.AuthCognitoUserPoolId),
|
114 | AwsRegion: cloudform_types_1.Refs.Region,
|
115 | DefaultAction: 'ALLOW',
|
116 | });
|
117 | break;
|
118 | case 'OPENID_CONNECT':
|
119 | if (!authConfig.defaultAuthentication.openIDConnectConfig) {
|
120 | throw new Error('openIDConnectConfig is not configured for defaultAuthentication');
|
121 | }
|
122 | properties.OpenIDConnectConfig = this.assignOpenIDConnectConfig(authConfig.defaultAuthentication.openIDConnectConfig);
|
123 | break;
|
124 | }
|
125 | if (authConfig.additionalAuthenticationProviders && authConfig.additionalAuthenticationProviders.length > 0) {
|
126 | const additionalAuthenticationProviders = new Array();
|
127 | for (const sourceProvider of authConfig.additionalAuthenticationProviders) {
|
128 | let provider;
|
129 | switch (sourceProvider.authenticationType) {
|
130 | case 'AMAZON_COGNITO_USER_POOLS':
|
131 | provider = {
|
132 | AuthenticationType: 'AMAZON_COGNITO_USER_POOLS',
|
133 | UserPoolConfig: new graphQlApi_1.UserPoolConfig({
|
134 | UserPoolId: cloudform_types_1.Fn.Ref(graphql_transformer_common_1.ResourceConstants.PARAMETERS.AuthCognitoUserPoolId),
|
135 | AwsRegion: cloudform_types_1.Refs.Region,
|
136 | }),
|
137 | };
|
138 | break;
|
139 | case 'API_KEY':
|
140 | provider = {
|
141 | AuthenticationType: 'API_KEY',
|
142 | };
|
143 | break;
|
144 | case 'AWS_IAM':
|
145 | provider = {
|
146 | AuthenticationType: 'AWS_IAM',
|
147 | };
|
148 | break;
|
149 | case 'OPENID_CONNECT':
|
150 | if (!sourceProvider.openIDConnectConfig) {
|
151 | throw new Error('openIDConnectConfig is not configured for provider');
|
152 | }
|
153 | provider = {
|
154 | AuthenticationType: 'OPENID_CONNECT',
|
155 | OpenIDConnectConfig: this.assignOpenIDConnectConfig(sourceProvider.openIDConnectConfig),
|
156 | };
|
157 | break;
|
158 | }
|
159 | additionalAuthenticationProviders.push(provider);
|
160 | }
|
161 | properties.AdditionalAuthenticationProviders = additionalAuthenticationProviders;
|
162 | }
|
163 | return new graphQlApi_1.default(properties);
|
164 | }
|
165 | assignOpenIDConnectConfig(config) {
|
166 | return new graphQlApi_1.OpenIDConnectConfig({
|
167 | Issuer: config.issuerUrl,
|
168 | ClientId: config.clientId,
|
169 | IatTTL: config.iatTTL,
|
170 | AuthTTL: config.authTTL,
|
171 | });
|
172 | }
|
173 | blankResolver(type, field) {
|
174 | return new cloudform_types_1.AppSync.Resolver({
|
175 | ApiId: cloudform_types_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
|
176 | DataSourceName: 'NONE',
|
177 | FieldName: field,
|
178 | TypeName: type,
|
179 | RequestMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.obj({
|
180 | version: graphql_mapping_template_1.str('2017-02-28'),
|
181 | payload: graphql_mapping_template_1.obj({}),
|
182 | })),
|
183 | ResponseMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.ref(`util.toJson($context.source.${field})`)),
|
184 | });
|
185 | }
|
186 | noneDataSource() {
|
187 | return new cloudform_types_1.AppSync.DataSource({
|
188 | ApiId: cloudform_types_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
|
189 | Name: 'NONE',
|
190 | Type: 'NONE',
|
191 | });
|
192 | }
|
193 | staticGroupAuthorizationExpression(rules, field) {
|
194 | if (!rules || rules.length === 0) {
|
195 | return graphql_mapping_template_1.comment(`No Static Group Authorization Rules`);
|
196 | }
|
197 | const variableToSet = this.getStaticAuthorizationVariable(field);
|
198 | let groupAuthorizationExpressions = [];
|
199 | for (const rule of rules) {
|
200 | const groups = rule.groups;
|
201 | const groupClaimAttribute = rule.groupClaim || constants_1.DEFAULT_GROUP_CLAIM;
|
202 | if (groups) {
|
203 | groupAuthorizationExpressions = groupAuthorizationExpressions.concat(graphql_mapping_template_1.comment(`Authorization rule: { allow: groups, groups: ${JSON.stringify(groups)}, groupClaim: "${groupClaimAttribute}" }`), this.setUserGroups(rule.groupClaim), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('allowedGroups'), graphql_mapping_template_1.list(groups.map(s => graphql_mapping_template_1.str(s)))), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('userGroup'), graphql_mapping_template_1.ref('userGroups'), [
|
204 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedGroups.contains($userGroup)`), graphql_mapping_template_1.compoundExpression([graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')), graphql_mapping_template_1.raw('#break')])),
|
205 | ]));
|
206 | }
|
207 | }
|
208 | const staticGroupAuthorizedVariable = this.getStaticAuthorizationVariable(field);
|
209 | return graphql_mapping_template_1.block('Static Group Authorization Checks', [
|
210 | graphql_mapping_template_1.raw(`#set($${staticGroupAuthorizedVariable} = $util.defaultIfNull(
|
211 | $${staticGroupAuthorizedVariable}, false))`),
|
212 | ...groupAuthorizationExpressions,
|
213 | ]);
|
214 | }
|
215 | dynamicGroupAuthorizationExpressionForCreateOperations(rules, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable) {
|
216 | if (!rules || rules.length === 0) {
|
217 | return graphql_mapping_template_1.comment(`No Dynamic Group Authorization Rules`);
|
218 | }
|
219 | return graphql_mapping_template_1.block('Dynamic Group Authorization Checks', [
|
220 | this.dynamicAuthorizationExpressionForCreate(rules, variableToCheck, variableToSet),
|
221 | ]);
|
222 | }
|
223 | dynamicGroupAuthorizationExpressionForCreateOperationsByField(rules, fieldToCheck, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable) {
|
224 | if (!rules || rules.length === 0) {
|
225 | return graphql_mapping_template_1.comment(`No dynamic group authorization rules for field "${fieldToCheck}"`);
|
226 | }
|
227 | let groupAuthorizationExpression = this.dynamicAuthorizationExpressionForCreate(rules, variableToCheck, variableToSet, rule => `Authorization rule on field "${fieldToCheck}": { allow: ${rule.allow}, \
|
228 | groupsField: "${rule.groupsField || constants_1.DEFAULT_GROUPS_FIELD}", groupClaim: "${rule.groupClaim || constants_1.DEFAULT_GROUP_CLAIM}" }`);
|
229 | return graphql_mapping_template_1.block(`Dynamic group authorization rules for field "${fieldToCheck}"`, [groupAuthorizationExpression]);
|
230 | }
|
231 | dynamicAuthorizationExpressionForCreate(rules, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable, formatComment) {
|
232 | let groupAuthorizationExpressions = [];
|
233 | for (const rule of rules) {
|
234 | const groupsAttribute = rule.groupsField || constants_1.DEFAULT_GROUPS_FIELD;
|
235 | const groupClaimAttribute = rule.groupClaim || constants_1.DEFAULT_GROUP_CLAIM;
|
236 | groupAuthorizationExpressions = groupAuthorizationExpressions.concat(formatComment
|
237 | ? graphql_mapping_template_1.comment(formatComment(rule))
|
238 | : graphql_mapping_template_1.comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}"`), this.setUserGroups(rule.groupClaim), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw(`$util.defaultIfNull($${variableToSet}, false)`)), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('userGroup'), graphql_mapping_template_1.ref('userGroups'), [
|
239 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isList($ctx.args.input.${groupsAttribute})`), graphql_mapping_template_1.iff(graphql_mapping_template_1.ref(`${variableToCheck}.${groupsAttribute}.contains($userGroup)`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))),
|
240 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isString($ctx.args.input.${groupsAttribute})`), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$ctx.args.input.${groupsAttribute} == $userGroup`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))),
|
241 | ]));
|
242 | }
|
243 | return graphql_mapping_template_1.compoundExpression(groupAuthorizationExpressions);
|
244 | }
|
245 | ownerAuthorizationExpressionForCreateOperations(rules, fieldIsList, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable) {
|
246 | if (!rules || rules.length === 0) {
|
247 | return graphql_mapping_template_1.comment(`No Owner Authorization Rules`);
|
248 | }
|
249 | return graphql_mapping_template_1.block('Owner Authorization Checks', [
|
250 | this.ownershipAuthorizationExpressionForCreate(rules, fieldIsList, variableToCheck, variableToSet),
|
251 | ]);
|
252 | }
|
253 | ownerAuthorizationExpressionForSubscriptions(rules, variableToCheck = 'ctx.args', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable) {
|
254 | if (!rules || rules.length === 0) {
|
255 | return graphql_mapping_template_1.comment(`No Owner Authorization Rules`);
|
256 | }
|
257 | return graphql_mapping_template_1.block('Owner Authorization Checks', [
|
258 | this.ownershipAuthorizationExpressionForSubscriptions(rules, variableToCheck, variableToSet),
|
259 | ]);
|
260 | }
|
261 | ownershipAuthorizationExpressionForSubscriptions(rules, variableToCheck = 'ctx.args', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable, formatComment) {
|
262 | let ownershipAuthorizationExpressions = [];
|
263 | let ruleNumber = 0;
|
264 | for (const rule of rules) {
|
265 | const ownerAttribute = rule.ownerField || constants_1.DEFAULT_OWNER_FIELD;
|
266 | const rawUsername = rule.identityField || rule.identityClaim || constants_1.DEFAULT_IDENTITY_FIELD;
|
267 | const isUser = isUsername(rawUsername);
|
268 | const identityAttribute = replaceIfUsername(rawUsername);
|
269 | const allowedOwnersVariable = `allowedOwners${ruleNumber}`;
|
270 | ownershipAuthorizationExpressions = ownershipAuthorizationExpressions.concat(formatComment
|
271 | ? graphql_mapping_template_1.comment(formatComment(rule))
|
272 | : graphql_mapping_template_1.comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(allowedOwnersVariable), graphql_mapping_template_1.raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)), isUser
|
273 | ?
|
274 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"),
|
275 | $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}"))`))
|
276 | : graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}")`)), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isList($${allowedOwnersVariable})`), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('allowedOwner'), graphql_mapping_template_1.ref(allowedOwnersVariable), [
|
277 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedOwner == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true'))),
|
278 | ])), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isString($${allowedOwnersVariable})`), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$${allowedOwnersVariable} == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))));
|
279 | ruleNumber++;
|
280 | }
|
281 | return graphql_mapping_template_1.compoundExpression([graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw(`false`)), ...ownershipAuthorizationExpressions]);
|
282 | }
|
283 | ownerAuthorizationExpressionForCreateOperationsByField(rules, fieldToCheck, fieldIsList, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable) {
|
284 | if (!rules || rules.length === 0) {
|
285 | return graphql_mapping_template_1.comment(`No Owner Authorization Rules`);
|
286 | }
|
287 | return graphql_mapping_template_1.block(`Owner authorization rules for field "${fieldToCheck}"`, [
|
288 | this.ownershipAuthorizationExpressionForCreate(rules, fieldIsList, variableToCheck, variableToSet, rule => `Authorization rule: { allow: ${rule.allow}, \
|
289 | ownerField: "${rule.ownerField || constants_1.DEFAULT_OWNER_FIELD}", \
|
290 | identityClaim: "${rule.identityField || rule.identityClaim || constants_1.DEFAULT_IDENTITY_FIELD}" }`),
|
291 | ]);
|
292 | }
|
293 | ownershipAuthorizationExpressionForCreate(rules, fieldIsList, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable, formatComment) {
|
294 | let ownershipAuthorizationExpressions = [];
|
295 | let ruleNumber = 0;
|
296 | for (const rule of rules) {
|
297 | const ownerAttribute = rule.ownerField || constants_1.DEFAULT_OWNER_FIELD;
|
298 | const rawUsername = rule.identityField || rule.identityClaim || constants_1.DEFAULT_IDENTITY_FIELD;
|
299 | const isUser = isUsername(rawUsername);
|
300 | const identityAttribute = replaceIfUsername(rawUsername);
|
301 | const ownerFieldIsList = fieldIsList(ownerAttribute);
|
302 | const allowedOwnersVariable = `allowedOwners${ruleNumber}`;
|
303 | ownershipAuthorizationExpressions = ownershipAuthorizationExpressions.concat(formatComment
|
304 | ? graphql_mapping_template_1.comment(formatComment(rule))
|
305 | : graphql_mapping_template_1.comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(allowedOwnersVariable), graphql_mapping_template_1.raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)), isUser
|
306 | ?
|
307 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}"))`))
|
308 | : graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}")`)), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isList($${allowedOwnersVariable})`), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('allowedOwner'), graphql_mapping_template_1.ref(allowedOwnersVariable), [
|
309 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedOwner == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true'))),
|
310 | ])), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isString($${allowedOwnersVariable})`), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$${allowedOwnersVariable} == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))));
|
311 | if (!ownerFieldIsList) {
|
312 | ownershipAuthorizationExpressions.push(graphql_mapping_template_1.iff(graphql_mapping_template_1.and([graphql_mapping_template_1.raw(`$util.isNull($${allowedOwnersVariable})`), graphql_mapping_template_1.parens(graphql_mapping_template_1.raw(`! $${variableToCheck}.containsKey("${ownerAttribute}")`))]), graphql_mapping_template_1.compoundExpression([
|
313 | graphql_mapping_template_1.qref(`$${variableToCheck}.put("${ownerAttribute}", $identityValue)`),
|
314 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')),
|
315 | ])));
|
316 | }
|
317 | else {
|
318 | ownershipAuthorizationExpressions.push(graphql_mapping_template_1.iff(graphql_mapping_template_1.and([graphql_mapping_template_1.raw(`$util.isNull($${allowedOwnersVariable})`), graphql_mapping_template_1.parens(graphql_mapping_template_1.raw(`! $${variableToCheck}.containsKey("${ownerAttribute}")`))]), graphql_mapping_template_1.compoundExpression([
|
319 | graphql_mapping_template_1.qref(`$${variableToCheck}.put("${ownerAttribute}", ["$identityValue"])`),
|
320 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')),
|
321 | ])));
|
322 | }
|
323 | ruleNumber++;
|
324 | }
|
325 | return graphql_mapping_template_1.compoundExpression([graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw(`false`)), ...ownershipAuthorizationExpressions]);
|
326 | }
|
327 | dynamicGroupAuthorizationExpressionForUpdateOrDeleteOperations(rules, fieldIsList, fieldBeingProtected, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable) {
|
328 | const fieldMention = fieldBeingProtected ? ` for field "${fieldBeingProtected}"` : '';
|
329 | if (!rules || rules.length === 0) {
|
330 | return graphql_mapping_template_1.comment(`No dynamic group authorization rules${fieldMention}`);
|
331 | }
|
332 | let groupAuthorizationExpressions = [];
|
333 | let ruleNumber = 0;
|
334 | for (const rule of rules) {
|
335 | const groupsAttribute = rule.groupsField || constants_1.DEFAULT_GROUPS_FIELD;
|
336 | const groupsAttributeName = fieldBeingProtected
|
337 | ? `${fieldBeingProtected}_groupsAttribute${ruleNumber}`
|
338 | : `groupsAttribute${ruleNumber}`;
|
339 | const groupName = fieldBeingProtected ? `${fieldBeingProtected}_group${ruleNumber}` : `group${ruleNumber}`;
|
340 | const groupClaimAttribute = rule.groupClaim || constants_1.DEFAULT_GROUP_CLAIM;
|
341 | const groupsFieldIsList = fieldIsList(groupsAttribute);
|
342 | groupAuthorizationExpressions = groupAuthorizationExpressions.concat(graphql_mapping_template_1.comment(`Authorization rule${fieldMention}: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}"}`), this.setUserGroups(rule.groupClaim), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('userGroup'), graphql_mapping_template_1.ref('userGroups'), [
|
343 | groupsFieldIsList
|
344 | ? graphql_mapping_template_1.raw(`$util.qr($groupAuthExpressions.add("contains(#${groupsAttributeName}, :${groupName}$foreach.count)"))`)
|
345 | : graphql_mapping_template_1.raw(`$util.qr($groupAuthExpressions.add("#${groupsAttributeName} = :${groupName}$foreach.count"))`),
|
346 | graphql_mapping_template_1.raw(`$util.qr($groupAuthExpressionValues.put(":${groupName}$foreach.count", { "S": $userGroup }))`),
|
347 | ]), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('$userGroups.size() > 0'), graphql_mapping_template_1.raw(`$util.qr($groupAuthExpressionNames.put("#${groupsAttributeName}", "${groupsAttribute}"))`)));
|
348 | ruleNumber++;
|
349 | }
|
350 | return graphql_mapping_template_1.block('Dynamic group authorization checks', [
|
351 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('groupAuthExpressions'), graphql_mapping_template_1.list([])),
|
352 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('groupAuthExpressionValues'), graphql_mapping_template_1.obj({})),
|
353 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('groupAuthExpressionNames'), graphql_mapping_template_1.obj({})),
|
354 | ...groupAuthorizationExpressions,
|
355 | ]);
|
356 | }
|
357 | ownerAuthorizationExpressionForUpdateOrDeleteOperations(rules, fieldIsList, fieldBeingProtected, variableToCheck = 'ctx.args.input', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable) {
|
358 | const fieldMention = fieldBeingProtected ? ` for field "${fieldBeingProtected}"` : '';
|
359 | if (!rules || rules.length === 0) {
|
360 | return graphql_mapping_template_1.comment(`No owner authorization rules${fieldMention}`);
|
361 | }
|
362 | let ownerAuthorizationExpressions = [];
|
363 | let ruleNumber = 0;
|
364 | for (const rule of rules) {
|
365 | const ownerAttribute = rule.ownerField || constants_1.DEFAULT_OWNER_FIELD;
|
366 | const rawUsername = rule.identityField || rule.identityClaim || constants_1.DEFAULT_IDENTITY_FIELD;
|
367 | const isUser = isUsername(rawUsername);
|
368 | const identityAttribute = replaceIfUsername(rawUsername);
|
369 | const ownerFieldIsList = fieldIsList(ownerAttribute);
|
370 | const ownerName = fieldBeingProtected ? `${fieldBeingProtected}_owner${ruleNumber}` : `owner${ruleNumber}`;
|
371 | const identityName = fieldBeingProtected ? `${fieldBeingProtected}_identity${ruleNumber}` : `identity${ruleNumber}`;
|
372 | ownerAuthorizationExpressions.push(graphql_mapping_template_1.comment(`Authorization rule${fieldMention}: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`));
|
373 | if (ownerFieldIsList) {
|
374 | ownerAuthorizationExpressions.push(graphql_mapping_template_1.raw(`$util.qr($ownerAuthExpressions.add("contains(#${ownerName}, :${identityName})"))`));
|
375 | }
|
376 | else {
|
377 | ownerAuthorizationExpressions.push(graphql_mapping_template_1.raw(`$util.qr($ownerAuthExpressions.add("#${ownerName} = :${identityName}"))`));
|
378 | }
|
379 | ownerAuthorizationExpressions = ownerAuthorizationExpressions.concat(graphql_mapping_template_1.raw(`$util.qr($ownerAuthExpressionNames.put("#${ownerName}", "${ownerAttribute}"))`), isUser
|
380 | ? graphql_mapping_template_1.raw(`$util.qr($ownerAuthExpressionValues.put(":${identityName}", $util.dynamodb.toDynamoDB($util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}")))))`)
|
381 | : graphql_mapping_template_1.raw(`$util.qr($ownerAuthExpressionValues.put(":${identityName}", $util.dynamodb.toDynamoDB($util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}"))))`));
|
382 | ruleNumber++;
|
383 | }
|
384 | return graphql_mapping_template_1.block('Owner Authorization Checks', [
|
385 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('ownerAuthExpressions'), graphql_mapping_template_1.list([])),
|
386 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('ownerAuthExpressionValues'), graphql_mapping_template_1.obj({})),
|
387 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('ownerAuthExpressionNames'), graphql_mapping_template_1.obj({})),
|
388 | ...ownerAuthorizationExpressions,
|
389 | ]);
|
390 | }
|
391 | dynamicGroupAuthorizationExpressionForReadOperations(rules, variableToCheck = 'ctx.result', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable, defaultValue = graphql_mapping_template_1.raw(`$util.defaultIfNull($${variableToSet}, false)`)) {
|
392 | if (!rules || rules.length === 0) {
|
393 | return graphql_mapping_template_1.comment(`No Dynamic Group Authorization Rules`);
|
394 | }
|
395 | let groupAuthorizationExpressions = [];
|
396 | for (const rule of rules) {
|
397 | const groupsAttribute = rule.groupsField || constants_1.DEFAULT_GROUPS_FIELD;
|
398 | const groupClaimAttribute = rule.groupClaim || constants_1.DEFAULT_GROUP_CLAIM;
|
399 | groupAuthorizationExpressions = groupAuthorizationExpressions.concat(graphql_mapping_template_1.comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}" }`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('allowedGroups'), graphql_mapping_template_1.ref(`util.defaultIfNull($${variableToCheck}.${groupsAttribute}, [])`)), this.setUserGroups(rule.groupClaim), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('userGroup'), graphql_mapping_template_1.ref('userGroups'), [
|
400 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('$util.isList($allowedGroups)'), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedGroups.contains($userGroup)`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))),
|
401 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isString($allowedGroups)`), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedGroups == $userGroup`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))),
|
402 | ]));
|
403 | }
|
404 | return graphql_mapping_template_1.block('Dynamic Group Authorization Checks', [graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), defaultValue), ...groupAuthorizationExpressions]);
|
405 | }
|
406 | ownerAuthorizationExpressionForReadOperations(rules, variableToCheck = 'ctx.result', variableToSet = graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable, defaultValue = graphql_mapping_template_1.raw(`$util.defaultIfNull($${variableToSet}, false)`)) {
|
407 | if (!rules || rules.length === 0) {
|
408 | return graphql_mapping_template_1.comment(`No Owner Authorization Rules`);
|
409 | }
|
410 | let ownerAuthorizationExpressions = [];
|
411 | let ruleNumber = 0;
|
412 | for (const rule of rules) {
|
413 | const ownerAttribute = rule.ownerField || constants_1.DEFAULT_OWNER_FIELD;
|
414 | const rawUsername = rule.identityField || rule.identityClaim || constants_1.DEFAULT_IDENTITY_FIELD;
|
415 | const isUser = isUsername(rawUsername);
|
416 | const identityAttribute = replaceIfUsername(rawUsername);
|
417 | const allowedOwnersVariable = `allowedOwners${ruleNumber}`;
|
418 | ownerAuthorizationExpressions = ownerAuthorizationExpressions.concat(graphql_mapping_template_1.comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(allowedOwnersVariable), graphql_mapping_template_1.ref(`${variableToCheck}.${ownerAttribute}`)), isUser
|
419 | ?
|
420 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}"))`))
|
421 | : graphql_mapping_template_1.set(graphql_mapping_template_1.ref('identityValue'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${graphql_transformer_common_1.NONE_VALUE}")`)), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isList($${allowedOwnersVariable})`), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('allowedOwner'), graphql_mapping_template_1.ref(allowedOwnersVariable), [
|
422 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$allowedOwner == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true'))),
|
423 | ])), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$util.isString($${allowedOwnersVariable})`), graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$${allowedOwnersVariable} == $identityValue`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), graphql_mapping_template_1.raw('true')))));
|
424 | ruleNumber++;
|
425 | }
|
426 | return graphql_mapping_template_1.block('Owner Authorization Checks', [graphql_mapping_template_1.set(graphql_mapping_template_1.ref(variableToSet), defaultValue), ...ownerAuthorizationExpressions]);
|
427 | }
|
428 | throwIfSubscriptionUnauthorized() {
|
429 | const ifUnauthThrow = graphql_mapping_template_1.iff(graphql_mapping_template_1.not(graphql_mapping_template_1.parens(graphql_mapping_template_1.or([
|
430 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsStaticGroupAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
431 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
432 | ]))), graphql_mapping_template_1.raw('$util.unauthorized()'));
|
433 | return graphql_mapping_template_1.block('Throw if unauthorized', [ifUnauthThrow]);
|
434 | }
|
435 | throwIfUnauthorized(field) {
|
436 | const staticGroupAuthorizedVariable = this.getStaticAuthorizationVariable(field);
|
437 | const ifUnauthThrow = graphql_mapping_template_1.iff(graphql_mapping_template_1.not(graphql_mapping_template_1.parens(graphql_mapping_template_1.or([
|
438 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(staticGroupAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
439 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
440 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
441 | ]))), graphql_mapping_template_1.raw('$util.unauthorized()'));
|
442 | return graphql_mapping_template_1.block('Throw if unauthorized', [ifUnauthThrow]);
|
443 | }
|
444 | throwIfStaticGroupUnauthorized(field) {
|
445 | const staticGroupAuthorizedVariable = this.getStaticAuthorizationVariable(field);
|
446 | const ifUnauthThrow = graphql_mapping_template_1.iff(graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(staticGroupAuthorizedVariable), graphql_mapping_template_1.raw('false')), graphql_mapping_template_1.raw('$util.unauthorized()'));
|
447 | return graphql_mapping_template_1.block('Throw if unauthorized', [ifUnauthThrow]);
|
448 | }
|
449 | throwIfNotStaticGroupAuthorizedOrAuthConditionIsEmpty(field) {
|
450 | const staticGroupAuthorizedVariable = this.getStaticAuthorizationVariable(field);
|
451 | const ifUnauthThrow = graphql_mapping_template_1.iff(graphql_mapping_template_1.not(graphql_mapping_template_1.parens(graphql_mapping_template_1.or([graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(staticGroupAuthorizedVariable), graphql_mapping_template_1.raw('true')), graphql_mapping_template_1.parens(graphql_mapping_template_1.raw('$totalAuthExpression != ""'))]))), graphql_mapping_template_1.raw('$util.unauthorized()'));
|
452 | return graphql_mapping_template_1.block('Throw if unauthorized', [ifUnauthThrow]);
|
453 | }
|
454 | collectAuthCondition() {
|
455 | return graphql_mapping_template_1.block('Collect Auth Condition', [
|
456 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition), graphql_mapping_template_1.raw(`$util.defaultIfNull($authCondition, ${graphql_mapping_template_1.print(graphql_mapping_template_1.obj({
|
457 | expression: graphql_mapping_template_1.str(''),
|
458 | expressionNames: graphql_mapping_template_1.obj({}),
|
459 | expressionValues: graphql_mapping_template_1.obj({}),
|
460 | }))})`)),
|
461 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str('')),
|
462 | graphql_mapping_template_1.comment('Add dynamic group auth conditions if they exist'),
|
463 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('groupAuthExpressions'), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('authExpr'), graphql_mapping_template_1.ref('groupAuthExpressions'), [
|
464 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str(`$totalAuthExpression $authExpr`)),
|
465 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('foreach.hasNext'), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str(`$totalAuthExpression OR`))),
|
466 | ])),
|
467 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('groupAuthExpressionNames'), graphql_mapping_template_1.raw(`$util.qr($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expressionNames.putAll($groupAuthExpressionNames))`)),
|
468 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('groupAuthExpressionValues'), graphql_mapping_template_1.raw(`$util.qr($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expressionValues.putAll($groupAuthExpressionValues))`)),
|
469 | graphql_mapping_template_1.comment('Add owner auth conditions if they exist'),
|
470 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$totalAuthExpression != "" && $ownerAuthExpressions && $ownerAuthExpressions.size() > 0`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str(`$totalAuthExpression OR`))),
|
471 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('ownerAuthExpressions'), graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('authExpr'), graphql_mapping_template_1.ref('ownerAuthExpressions'), [
|
472 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str(`$totalAuthExpression $authExpr`)),
|
473 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('foreach.hasNext'), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('totalAuthExpression'), graphql_mapping_template_1.str(`$totalAuthExpression OR`))),
|
474 | ])),
|
475 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('ownerAuthExpressionNames'), graphql_mapping_template_1.raw(`$util.qr($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expressionNames.putAll($ownerAuthExpressionNames))`)),
|
476 | graphql_mapping_template_1.iff(graphql_mapping_template_1.ref('ownerAuthExpressionValues'), graphql_mapping_template_1.raw(`$util.qr($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expressionValues.putAll($ownerAuthExpressionValues))`)),
|
477 | graphql_mapping_template_1.comment('Set final expression if it has changed.'),
|
478 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw(`$totalAuthExpression != ""`), graphql_mapping_template_1.ifElse(graphql_mapping_template_1.raw(`$util.isNullOrEmpty($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expression)`), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(`${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expression`), graphql_mapping_template_1.str(`($totalAuthExpression)`)), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(`${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expression`), graphql_mapping_template_1.str(`$${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition}.expression AND ($totalAuthExpression)`)))),
|
479 | ]);
|
480 | }
|
481 | appendItemIfLocallyAuthorized() {
|
482 | return graphql_mapping_template_1.iff(graphql_mapping_template_1.parens(graphql_mapping_template_1.or([
|
483 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsLocalDynamicGroupAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
484 | graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsLocalOwnerAuthorizedVariable), graphql_mapping_template_1.raw('true')),
|
485 | ])), graphql_mapping_template_1.qref('$items.add($item)'));
|
486 | }
|
487 | setUserGroups(customGroup) {
|
488 | if (customGroup) {
|
489 | return graphql_mapping_template_1.compoundExpression([
|
490 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('userGroups'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${customGroup}"), [])`)),
|
491 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('$util.isString($userGroups)'), graphql_mapping_template_1.ifElse(graphql_mapping_template_1.raw('$util.isList($util.parseJson($userGroups))'), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('userGroups'), graphql_mapping_template_1.raw('$util.parseJson($userGroups)')), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('userGroups'), graphql_mapping_template_1.raw('[$userGroups]')))),
|
492 | ]);
|
493 | }
|
494 | return graphql_mapping_template_1.set(graphql_mapping_template_1.ref('userGroups'), graphql_mapping_template_1.raw(`$util.defaultIfNull($ctx.identity.claims.get("${constants_1.DEFAULT_GROUP_CLAIM}"), [])`));
|
495 | }
|
496 | generateSubscriptionResolver(fieldName, subscriptionTypeName = 'Subscription') {
|
497 | return new cloudform_types_1.AppSync.Resolver({
|
498 | ApiId: cloudform_types_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
|
499 | DataSourceName: 'NONE',
|
500 | FieldName: fieldName,
|
501 | TypeName: subscriptionTypeName,
|
502 | RequestMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.raw(`{
|
503 | "version": "2018-05-29",
|
504 | "payload": {}
|
505 | }`)),
|
506 | ResponseMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.raw(`$util.toJson(null)`)),
|
507 | });
|
508 | }
|
509 | operationCheckExpression(operation, field) {
|
510 | return graphql_mapping_template_1.block('Checking for allowed operations which can return this field', [
|
511 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('operation'), graphql_mapping_template_1.raw('$util.defaultIfNull($context.source.operation, "null")')),
|
512 | graphql_mapping_template_1.ifElse(graphql_mapping_template_1.raw(`$operation == "${operation}"`), graphql_mapping_template_1.ref('util.toJson(null)'), graphql_mapping_template_1.ref(`util.toJson($context.source.${field})`)),
|
513 | ]);
|
514 | }
|
515 | setOperationExpression(operation) {
|
516 | return graphql_mapping_template_1.print(graphql_mapping_template_1.block('Setting the operation', [graphql_mapping_template_1.set(graphql_mapping_template_1.ref('context.result.operation'), graphql_mapping_template_1.str(operation))]));
|
517 | }
|
518 | getAuthModeCheckWrappedExpression(expectedAuthModes, expression) {
|
519 | if (!expectedAuthModes || expectedAuthModes.size === 0) {
|
520 | return expression;
|
521 | }
|
522 | const conditions = [];
|
523 | for (const expectedAuthMode of expectedAuthModes) {
|
524 | conditions.push(graphql_mapping_template_1.equals(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthMode), graphql_mapping_template_1.str(`${expectedAuthMode}`)));
|
525 | }
|
526 | return graphql_mapping_template_1.block('Check authMode and execute owner/group checks', [
|
527 | graphql_mapping_template_1.iff(conditions.length === 1 ? conditions[0] : graphql_mapping_template_1.or(conditions), expression),
|
528 | ]);
|
529 | }
|
530 | getAuthModeDeterminationExpression(authProviders, isUserPoolTheDefault) {
|
531 | if (!authProviders || authProviders.size === 0) {
|
532 | return graphql_mapping_template_1.comment(`No authentication mode determination needed`);
|
533 | }
|
534 | const expressions = [];
|
535 | for (const authProvider of authProviders) {
|
536 | if (authProvider === 'userPools') {
|
537 | const statements = [
|
538 | graphql_mapping_template_1.raw(`$util.isNullOrEmpty($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthMode})`),
|
539 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity)`)),
|
540 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.sub)`)),
|
541 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.issuer)`)),
|
542 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.username)`)),
|
543 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.claims)`)),
|
544 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.sourceIp)`)),
|
545 | ];
|
546 | if (isUserPoolTheDefault === true) {
|
547 | statements.push(graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.defaultAuthStrategy)`)));
|
548 | }
|
549 | const userPoolsExpression = graphql_mapping_template_1.iff(graphql_mapping_template_1.and(statements), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthMode), graphql_mapping_template_1.str(`userPools`)));
|
550 | expressions.push(userPoolsExpression);
|
551 | }
|
552 | else if (authProvider === 'oidc') {
|
553 | const oidcExpression = graphql_mapping_template_1.iff(graphql_mapping_template_1.and([
|
554 | graphql_mapping_template_1.raw(`$util.isNullOrEmpty($${graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthMode})`),
|
555 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity)`)),
|
556 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.sub)`)),
|
557 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.issuer)`)),
|
558 | graphql_mapping_template_1.not(graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.claims)`)),
|
559 | graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.username)`),
|
560 | graphql_mapping_template_1.raw(`$util.isNull($ctx.identity.sourceIp)`),
|
561 | ]), graphql_mapping_template_1.set(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthMode), graphql_mapping_template_1.str(`oidc`)));
|
562 | if (expressions.length > 0) {
|
563 | expressions.push(graphql_mapping_template_1.newline());
|
564 | }
|
565 | expressions.push(oidcExpression);
|
566 | }
|
567 | }
|
568 | return graphql_mapping_template_1.block('Determine request authentication mode', expressions);
|
569 | }
|
570 | getStaticAuthorizationVariable(field) {
|
571 | return field
|
572 | ? `${field.name.value}_${graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsStaticGroupAuthorizedVariable}`
|
573 | : graphql_transformer_common_1.ResourceConstants.SNIPPETS.IsStaticGroupAuthorizedVariable;
|
574 | }
|
575 | makeIAMPolicyForRole(isAuthPolicy, resources) {
|
576 | const policies = new Array();
|
577 | const authPiece = isAuthPolicy ? 'auth' : 'unauth';
|
578 | let policyResources = [];
|
579 | let resourceSize = 0;
|
580 | const MAX_BUILT_SIZE_BYTES = 6000;
|
581 | const RESOURCE_OVERHEAD = 100;
|
582 | const createPolicy = newPolicyResources => new cloudform_types_1.IAM.ManagedPolicy({
|
583 | Roles: [
|
584 | { Ref: `${authPiece}RoleName` },
|
585 | ],
|
586 | PolicyDocument: {
|
587 | Version: '2012-10-17',
|
588 | Statement: [
|
589 | {
|
590 | Effect: 'Allow',
|
591 | Action: ['appsync:GraphQL'],
|
592 | Resource: newPolicyResources,
|
593 | },
|
594 | ],
|
595 | },
|
596 | });
|
597 | for (const resource of resources) {
|
598 | const resourceParts = resource.split('/');
|
599 | if (resourceParts[1] !== 'null') {
|
600 | policyResources.push(cloudform_types_1.Fn.Sub('arn:aws:appsync:${AWS::Region}:${AWS::AccountId}:apis/${apiId}/types/${typeName}/fields/${fieldName}', {
|
601 | apiId: {
|
602 | 'Fn::GetAtt': ['GraphQLAPI', 'ApiId'],
|
603 | },
|
604 | typeName: resourceParts[0],
|
605 | fieldName: resourceParts[1],
|
606 | }));
|
607 | resourceSize += RESOURCE_OVERHEAD + resourceParts[0].length + resourceParts[1].length;
|
608 | }
|
609 | else {
|
610 | policyResources.push(cloudform_types_1.Fn.Sub('arn:aws:appsync:${AWS::Region}:${AWS::AccountId}:apis/${apiId}/types/${typeName}/*', {
|
611 | apiId: {
|
612 | 'Fn::GetAtt': ['GraphQLAPI', 'ApiId'],
|
613 | },
|
614 | typeName: resourceParts[0],
|
615 | }));
|
616 | resourceSize += RESOURCE_OVERHEAD + resourceParts[0].length;
|
617 | }
|
618 | if (resourceSize > MAX_BUILT_SIZE_BYTES) {
|
619 | const policy = createPolicy(policyResources.slice(0, policyResources.length - 1));
|
620 | policies.push(policy);
|
621 | policyResources = policyResources.slice(-1);
|
622 | resourceSize = 0;
|
623 | }
|
624 | }
|
625 | if (policyResources.length > 0) {
|
626 | const policy = createPolicy(policyResources);
|
627 | policies.push(policy);
|
628 | }
|
629 | return policies;
|
630 | }
|
631 | makeESItemsExpression(includeVersion) {
|
632 | return graphql_mapping_template_1.compoundExpression([
|
633 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('es_items'), graphql_mapping_template_1.list([])),
|
634 | graphql_mapping_template_1.forEach(graphql_mapping_template_1.ref('entry'), graphql_mapping_template_1.ref('context.result.hits.hits'), [
|
635 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('!$foreach.hasNext'), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('nextToken'), graphql_mapping_template_1.ref('entry.sort.get(0)'))),
|
636 | ...this.getSourceMapper(includeVersion),
|
637 | ]),
|
638 | ]);
|
639 | }
|
640 | makeESToGQLExpression() {
|
641 | return graphql_mapping_template_1.compoundExpression([
|
642 | graphql_mapping_template_1.set(graphql_mapping_template_1.ref('es_response'), graphql_mapping_template_1.obj({
|
643 | items: graphql_mapping_template_1.ref('es_items'),
|
644 | })),
|
645 | graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('$es_items.size() > 0'), graphql_mapping_template_1.compoundExpression([graphql_mapping_template_1.qref('$es_response.put("nextToken", $nextToken)'), graphql_mapping_template_1.qref('$es_response.put("total", $es_items.size())')])),
|
646 | graphql_mapping_template_1.toJson(graphql_mapping_template_1.ref('es_response')),
|
647 | ]);
|
648 | }
|
649 | }
|
650 | exports.ResourceFactory = ResourceFactory;
|
651 |
|
\ | No newline at end of file |