Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
private authorizationExpressionForListResult(rules: AuthRule[]) {
// Break the rules out by strategy.
const staticGroupAuthorizationRules = this.getStaticGroupRules(rules)
const dynamicGroupAuthorizationRules = this.getDynamicGroupRules(rules)
const ownerAuthorizationRules = this.getOwnerRules(rules)
// Generate the expressions to validate each strategy.
const staticGroupAuthorizationExpression = this.resources.staticGroupAuthorizationExpression(staticGroupAuthorizationRules)
// In list queries, the dynamic group and ownership authorization checks
// occur on a per item basis. The helpers take the variable names
// as parameters to allow for this use case.
const dynamicGroupAuthorizationExpression = this.resources.dynamicGroupAuthorizationExpressionForReadOperations(
dynamicGroupAuthorizationRules,
'item',
ResourceConstants.SNIPPETS.IsLocalDynamicGroupAuthorizedVariable,
raw(`false`)
)
const ownerAuthorizationExpression = this.resources.ownerAuthorizationExpressionForReadOperations(
ownerAuthorizationRules,
'item',
ResourceConstants.SNIPPETS.IsLocalOwnerAuthorizedVariable,
raw(`false`)
)
const appendIfLocallyAuthorized = this.resources.appendItemIfLocallyAuthorized()
const ifNotStaticallyAuthedFilterObjects = iff(
raw(`! $${ResourceConstants.SNIPPETS.IsStaticGroupAuthorizedVariable}`),
compoundExpression([
set(ref('items'), list([])),
forEach(
ref('item'),
private augmentDeleteMutation(ctx: TransformerContext, typeName: string, versionField: string, versionInput: string) {
const mutationResolverLogicalId = ResolverResourceIDs.DynamoDBDeleteResolverResourceID(typeName);
const snippet = printBlock(`Inject @versioned condition.`)(
compoundExpression([
set(
ref(ResourceConstants.SNIPPETS.VersionedCondition),
obj({
expression: str(`#${versionField} = :${versionInput}`),
expressionValues: obj({
[`:${versionInput}`]: raw(`$util.dynamodb.toDynamoDB($ctx.args.input.${versionInput})`),
}),
expressionNames: obj({
[`#${versionField}`]: str(`${versionField}`),
}),
})
),
qref(`$ctx.args.input.remove("${versionInput}")`),
])
);
const resolver = ctx.getResource(mutationResolverLogicalId);
if (resolver) {
resolver.Properties.RequestMappingTemplate = snippet + '\n\n' + resolver.Properties.RequestMappingTemplate;
public makeGetResolver(type: string, nameOverride?: string, isSyncEnabled: boolean = false, queryTypeName: string = 'Query') {
const fieldName = nameOverride ? nameOverride : graphqlName('get' + toUpper(type));
return new AppSync.Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
FieldName: fieldName,
TypeName: queryTypeName,
RequestMappingTemplate: print(
DynamoDBMappingTemplate.getItem({
key: ifElse(
ref(ResourceConstants.SNIPPETS.ModelObjectKey),
raw(`$util.toJson(\$${ResourceConstants.SNIPPETS.ModelObjectKey})`),
obj({
id: ref('util.dynamodb.toDynamoDBJson($ctx.args.id)'),
}),
true
),
isSyncEnabled,
})
),
ResponseMappingTemplate: isSyncEnabled ? print(DynamoDBMappingTemplate.dynamoDBResponse()) : print(ref('util.toJson($ctx.result)')),
});
}
])
),
iff(
and([ref('condition.expressionValues'), raw('$condition.expressionValues.size() == 0')]),
set(
ref('condition'),
obj({
expression: ref('condition.expression'),
expressionNames: ref('condition.expressionNames'),
})
)
),
DynamoDBMappingTemplate.deleteItem({
key: ifElse(
ref(ResourceConstants.SNIPPETS.ModelObjectKey),
raw(`$util.toJson(\$${ResourceConstants.SNIPPETS.ModelObjectKey})`),
obj({
id: ref('util.dynamodb.toDynamoDBJson($ctx.args.input.id)'),
}),
true
),
condition: ref('util.toJson($condition)'),
isSyncEnabled,
}),
])
),
ResponseMappingTemplate: isSyncEnabled ? print(DynamoDBMappingTemplate.dynamoDBResponse()) : print(ref('util.toJson($ctx.result)')),
...(syncConfig && { SyncConfig: SyncUtils.syncResolverConfig(syncConfig) }),
});
}
}
function setQuerySnippet(definition: ObjectTypeDefinitionNode, directive: DirectiveNode, ctx: TransformerContext) {
const args: KeyArguments = getDirectiveArguments(directive);
const keys = args.fields;
const keyTypes = keys.map(k => {
const field = definition.fields.find(f => f.name.value === k);
return attributeTypeFromType(field.type, ctx);
})
return block(`Set query expression for @key`, [
set(ref(ResourceConstants.SNIPPETS.ModelQueryExpression), obj({})),
applyKeyExpressionForCompositeKey(keys, keyTypes, ResourceConstants.SNIPPETS.ModelQueryExpression)
])
}
function ensureCompositeKeySnippet(dir: DirectiveNode): string {
const args: KeyArguments = getDirectiveArguments(dir);
const argsPrefix = 'ctx.args.input';
if (args.fields.length > 2) {
const rangeKeyFields = args.fields.slice(1);
const condensedSortKey = condenseRangeKey(rangeKeyFields);
const dynamoDBFriendlySortKeyName = toCamelCase(rangeKeyFields.map(f => graphqlName(f)));
const condensedSortKeyValue = condenseRangeKey(
rangeKeyFields.map(keyField => `\${${argsPrefix}.${keyField}}`)
);
return print(compoundExpression([
ifElse(
raw(`$util.isNull($${ResourceConstants.SNIPPETS.DynamoDBNameOverrideMap})`),
set(ref(ResourceConstants.SNIPPETS.DynamoDBNameOverrideMap), obj({
[condensedSortKey]: str(dynamoDBFriendlySortKeyName)
})),
qref(`$${ResourceConstants.SNIPPETS.DynamoDBNameOverrideMap}.put("${condensedSortKey}", "${dynamoDBFriendlySortKeyName}")`)
),
qref(`$ctx.args.input.put("${condensedSortKey}","${condensedSortKeyValue}")`)
]));
}
return '';
}
private setKeySnippet = (directive: DirectiveNode, isMutation: boolean = false) => {
const directiveArgs = getDirectiveArguments(directive);
const cmds: Expression[] = [set(
ref(ResourceConstants.SNIPPETS.ModelObjectKey),
modelObjectKey(directiveArgs, isMutation)
)];
return printBlock(`Set the primary @key`)(compoundExpression(cmds));
}
public ownershipAuthorizationExpressionForCreate(
rules: AuthRule[],
fieldIsList: (fieldName: string) => boolean,
variableToCheck: string = 'ctx.args.input',
variableToSet: string = ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable,
formatComment?: (rule: AuthRule) => string,
) {
let ownershipAuthorizationExpressions = []
let ruleNumber = 0;
for (const rule of rules) {
const ownerAttribute = rule.ownerField || DEFAULT_OWNER_FIELD
const rawUsername = rule.identityField || DEFAULT_IDENTITY_FIELD
const isUsern = isUsername(rawUsername)
const identityAttribute = replaceIfUsername(rawUsername)
const ownerFieldIsList = fieldIsList(ownerAttribute)
const allowedOwnersVariable = `allowedOwners${ruleNumber}`
ownershipAuthorizationExpressions = ownershipAuthorizationExpressions.concat(
formatComment ?
comment(formatComment(rule)) :
comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityField: "${identityAttribute}" }`),
set(ref(allowedOwnersVariable), raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)),
public ownershipAuthorizationExpressionForCreate(
rules: AuthRule[],
fieldIsList: (fieldName: string) => boolean,
variableToCheck: string = 'ctx.args.input',
variableToSet: string = ResourceConstants.SNIPPETS.IsOwnerAuthorizedVariable,
formatComment?: (rule: AuthRule) => string
) {
let ownershipAuthorizationExpressions = [];
let ruleNumber = 0;
for (const rule of rules) {
const ownerAttribute = rule.ownerField || DEFAULT_OWNER_FIELD;
const rawUsername = rule.identityField || rule.identityClaim || DEFAULT_IDENTITY_FIELD;
const isUser = isUsername(rawUsername);
const identityAttribute = replaceIfUsername(rawUsername);
const ownerFieldIsList = fieldIsList(ownerAttribute);
const allowedOwnersVariable = `allowedOwners${ruleNumber}`;
ownershipAuthorizationExpressions = ownershipAuthorizationExpressions.concat(
formatComment
? comment(formatComment(rule))
: comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`),
set(ref(allowedOwnersVariable), raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)),
const dynamicGroupAuthorizationExpression = this.resources.dynamicGroupAuthorizationExpressionForReadOperations(
dynamicGroupAuthorizationRules,
'item',
ResourceConstants.SNIPPETS.IsLocalDynamicGroupAuthorizedVariable,
raw(`false`)
)
const ownerAuthorizationExpression = this.resources.ownerAuthorizationExpressionForReadOperations(
ownerAuthorizationRules,
'item',
ResourceConstants.SNIPPETS.IsLocalOwnerAuthorizedVariable,
raw(`false`)
)
const appendIfLocallyAuthorized = this.resources.appendItemIfLocallyAuthorized()
const ifNotStaticallyAuthedFilterObjects = iff(
raw(`! $${ResourceConstants.SNIPPETS.IsStaticGroupAuthorizedVariable}`),
compoundExpression([
set(ref('items'), list([])),
forEach(
ref('item'),
ref('ctx.result.items'),
[
dynamicGroupAuthorizationExpression,
newline(),
ownerAuthorizationExpression,
newline(),
appendIfLocallyAuthorized
]
),
set(ref('ctx.result.items'), ref('items'))
])
)