在Groovy中实现DSL白名单

时间:2014-12-10 23:13:27

标签: groovy dsl

Groovy in Action提供以下代码,用于通过SecureASTCustomizer为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)

1 个答案:

答案 0 :(得分:2)

PLUS和朋友们现在在

import static org.codehaus.groovy.syntax.Types.*

你还需要

import org.codehaus.groovy.ast.stmt.* // for the classes in `statementsWhitelist`
import org.codehaus.groovy.ast.expr.* // for the classes in `expressionsWhitelist`

鉴于,这本书是从2009年开始的,你现在正在使用2.3范围内的常规,包/类位置只是随着时间的推移而变化,或者源代码从未在第一时间起作用。

您可能需要考虑一个IDE,它有助于为您查找类/创建import