3
Groovy in Action提供以下代碼,通過SecureASTCustomizer
爲DSL提供安全性。在Groovy中實現DSL白名單
// @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)