Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public makeESItemsExpression() {
// generate es expresion to appsync
return compoundExpression([
set(ref('es_items'), list([])),
forEach(ref('entry'), ref('context.result.hits.hits'), [
iff(raw('!$foreach.hasNext'), set(ref('nextToken'), ref('entry.sort.get(0)'))),
qref('$es_items.add($entry.get("_source"))'),
]),
]);
}
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)`)),
isUsern ?
// tslint:disable-next-line
set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`)) :
set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
// If a list of owners check for at least one.
iff(
raw(`$util.isList($${allowedOwnersVariable})`),
forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
iff(
raw(`$allowedOwner == $identityValue`),
set(ref(variableToSet), raw('true'))),
])
),
// If a single owner check for at least one.
iff(
raw(`$util.isString($${allowedOwnersVariable})`),
iff(
raw(`$${allowedOwnersVariable} == $identityValue`),
set(ref(variableToSet), raw('true'))),
)
)
// If the owner field is not a list and the user does not
// provide a value for the owner, set the owner automatically.
if (!ownerFieldIsList) {
? comment(formatComment(rule))
: comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`),
set(ref(allowedOwnersVariable), raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)),
isUser
? // tslint:disable-next-line
set(
ref('identityValue'),
raw(
`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`
)
)
: set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
// If a list of owners check for at least one.
iff(
raw(`$util.isList($${allowedOwnersVariable})`),
forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
iff(raw(`$allowedOwner == $identityValue`), set(ref(variableToSet), raw('true'))),
])
),
// If a single owner check for at least one.
iff(
raw(`$util.isString($${allowedOwnersVariable})`),
iff(raw(`$${allowedOwnersVariable} == $identityValue`), set(ref(variableToSet), raw('true')))
)
);
// If the owner field is not a list and the user does not
// provide a value for the owner, set the owner automatically.
if (!ownerFieldIsList) {
ownershipAuthorizationExpressions.push(
// If the owner is not provided set it automatically.
// If the user explicitly provides null this will be false and we leave it null.
iff(
): Expression {
const fieldMention = fieldBeingProtected ? ` for field "${fieldBeingProtected}"` : '';
if (!rules || rules.length === 0) {
return comment(`No dynamic group authorization rules${fieldMention}`)
}
let groupAuthorizationExpressions = []
let ruleNumber = 0
for (const rule of rules) {
const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD
const groupsAttributeName = `groupsAttribute${ruleNumber}`
const groupName = `group${ruleNumber}`
groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
comment(`Authorization rule${fieldMention}: { allow: ${rule.allow}, groupsField: "${groupsAttribute}" }`),
// Add the new auth expression and values
forEach(ref('userGroup'), ref('userGroups'), [
raw(`$util.qr($groupAuthExpressions.add("contains(#${groupsAttributeName}, :${groupName}$foreach.count)"))`),
raw(`$util.qr($groupAuthExpressionValues.put(":${groupName}$foreach.count", { "S": $userGroup }))`),
]),
iff(raw('$userGroups.size() > 0'), raw(`$util.qr($groupAuthExpressionNames.put("#${groupsAttributeName}", "${groupsAttribute}"))`)),
)
ruleNumber++
}
return block('Dynamic group authorization checks', [
this.setUserGroups(),
set(ref('groupAuthExpressions'), list([])),
set(ref('groupAuthExpressionValues'), obj({})),
set(ref('groupAuthExpressionNames'), obj({})),
...groupAuthorizationExpressions,
])
}
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'))
])
)
return compoundExpression([
staticGroupAuthorizationExpression,
newline(),
qref('$condition.put("expression", "$condition.expression AND attribute_exists(#id)")'),
qref('$condition.expressionNames.put("#id", "id")'),
])
),
]),
ifElse(
ref(ResourceConstants.SNIPPETS.ModelObjectKey),
compoundExpression([
set(
ref('condition'),
obj({
expression: str(''),
expressionNames: obj({}),
})
),
forEach(ref('entry'), ref(`${ResourceConstants.SNIPPETS.ModelObjectKey}.entrySet()`), [
ifElse(
raw('$velocityCount == 1'),
qref('$condition.put("expression", "attribute_exists(#keyCondition$velocityCount)")'),
qref('$condition.put(\
"expression", "$condition.expression AND attribute_exists(#keyCondition$velocityCount)")')
),
qref('$condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key")'),
]),
]),
set(
ref('condition'),
obj({
expression: str('attribute_exists(#id)'),
expressionNames: obj({
'#id': str('id'),
}),
type
)}Input.${this.typePrimaryKeyMap.get(type)}\'`;
} else {
selectSql = `SELECT * FROM ${type} WHERE ${this.typePrimaryKeyMap.get(type)}=$ctx.args.create${toUpper(
type
)}Input.${this.typePrimaryKeyMap.get(type)}`;
}
const reqFileName = `${mutationTypeName}.${fieldName}.req.vtl`;
const resFileName = `${mutationTypeName}.${fieldName}.res.vtl`;
const reqTemplate = print(
compoundExpression([
set(ref('cols'), list([])),
set(ref('vals'), list([])),
forEach(ref('entry'), ref(`ctx.args.create${toUpper(type)}Input.keySet()`), [
set(ref('discard'), ref(`cols.add($entry)`)),
set(ref('discard'), ref(`vals.add("'$ctx.args.create${toUpper(type)}Input[$entry]'")`)),
]),
set(ref('valStr'), ref('vals.toString().replace("[","(").replace("]",")")')),
set(ref('colStr'), ref('cols.toString().replace("[","(").replace("]",")")')),
RelationalDBMappingTemplate.rdsQuery({
statements: list([str(createSql), str(selectSql)]),
}),
])
);
const resTemplate = print(ref('utils.toJson($utils.parseJson($utils.rds.toJsonString($ctx.result))[1][0])'));
fs.writeFileSync(`${this.resolverFilePath}/${reqFileName}`, reqTemplate, 'utf8');
fs.writeFileSync(`${this.resolverFilePath}/${resFileName}`, resTemplate, 'utf8');
variableToCheck: string = 'ctx.args.input',
variableToSet: string = ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable,
formatComment?: (rule: AuthRule) => string,
) {
let groupAuthorizationExpressions = []
for (const rule of rules) {
const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD
groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
formatComment ?
comment(formatComment(rule)) :
comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}" }`),
set(
ref(variableToSet),
raw(`$util.defaultIfNull($${variableToSet}, false)`)
),
forEach(ref('userGroup'), ref('userGroups'), [
iff(
raw(`$util.isList($ctx.args.input.${groupsAttribute})`),
iff(
ref(`${variableToCheck}.${groupsAttribute}.contains($userGroup)`),
set(ref(variableToSet), raw('true'))
),
),
iff(
raw(`$util.isString($ctx.args.input.${groupsAttribute})`),
iff(
raw(`$ctx.args.input.${groupsAttribute} == $userGroup`),
set(ref(variableToSet), raw('true'))
),
)
])
)
obj({
"$context.args.sort.field": obj({
"order": str('$context.args.sort.direction')
})
})
),
str('_doc')
]),
list([]))
})
])
),
ResponseMappingTemplate: print(
compoundExpression([
set(ref('items'), list([])),
forEach(
ref('entry'),
ref('context.result.hits.hits'),
[
iff(
raw('!$foreach.hasNext'),
set(ref('nextToken'), str('$entry.sort.get(0)'))
),
qref('$items.add($entry.get("_source"))')
]
),
toJson(obj({
"items": ref('items'),
"total": ref('ctx.result.hits.total'),
"nextToken": ref('nextToken')
}))
])