首页 文章

在Groovy中实现DSL白名单

提问于
浏览
3

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 回答

  • 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范围内的groovy,包/类位置只是随着时间的推移而改变,或者源代码从未在第一时间起作用 .

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

相关问题