Groovy in Action предоставляет следующий код для обеспечения безопасности DSL через SecureASTCustomizer
.Внедрение белого списка DSL в Groovy
// @author: Groovy in Action
import org.codehaus.groovy.control.*
import org.codehaus.groovy.control.customizers.*
def secure = new SecureASTCustomizer()
secure.with {
closuresAllowed = false
methodDefinitionAllowed = false
importsWhitelist = []
staticImportsWhitelist = []
staticStarImportsWhitelist = ['java.lang.Math']
tokensWhitelist = [
PLUS, MINUS, MULTIPLY, DIVIDE, MOD, POWER,
PLUS_PLUS, MINUS_MINUS,
COMPARE_EQUAL, COMPARE_NOT_EQUAL,
COMPARE_LESS_THAN, COMPARE_LESS_THAN_EQUAL,
COMPARE_GREATER_THAN, COMPARE_GREATER_THAN_EQUAL,
]
constantTypesClassesWhiteList = [
Integer, Float, Long, Double, BigDecimal,
Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
]
receiversClassesWhiteList = [
Math, Integer, Float, Double, Long, BigDecimal
]
statementsWhitelist = [
BlockStatement, ExpressionStatement
]
expressionsWhitelist = [
BinaryExpression, ConstantExpression,
MethodCallExpression, StaticMethodCallExpression,
ArgumentListExpression, PropertyExpression,
UnaryMinusExpression, UnaryPlusExpression,
PrefixExpression, PostfixExpression,
TernaryExpression, ElvisOperatorExpression,
BooleanExpression, ClassExpression
]
}
def config = new CompilerConfiguration()
config.addCompilationCustomizers(secure)
def shell = new GroovyShell(config)
x = shell.evaluate '''
5 + 10
println("exiting...")
System.exit(0)
'''
println x
Однако, когда я запускаю этот код, я получаю ошибку во время выполнения.
Как исправить ошибку, чтобы получить пример работы - а именно DSL, который выполняет математические операции, не допуская каких-либо других типов команд, таких как System.exit(0)
.
>groovy WhiteListSimple.groovy
Caught: groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer
groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer
at WhiteListSimple$_run_closure1.doCall(WhiteListSimple.groovy:14)
at WhiteListSimple.run(WhiteListSimple.groovy:6)