GraalVM:禁止从脚本调用某些类的方法

rdrgkggo  于 2022-09-21  发布在  其他
关注(0)|答案(2)|浏览(251)

我们正在使用GraalVM来满足我们产品中的一些脚本要求。GraalVM的版本是21.2.0,我们使用的是JavaScript和Groovy。我们希望禁止在脚本中使用某些类上的某些方法。示例:

myest.js

var testService=Java.type('mypackage.TestService');
    new testService().forbiddenJavaMethod();  // this should not be called

TestService.Java

package mypackage;

    public class TestService{

        public void forbiddenJavaMethod(){
            // business logic
        }

    }

在Graal有办法实现这一点吗?我找不到一种方法来进行“方法”过滤。有没有其他方法来解决这个问题?

mkshixfv

mkshixfv1#

您可以在配置环境时配置主机访问权限。即

public Context.Builder allowHostAccess(HostAccess config)

Https://www.graalvm.org/truffle/javadoc/org/graalvm/polyglot/Context.Builder.html#allowHostAccess-org.graalvm.polyglot.HostAccess-

可以访问主机的位置

HostAccess.EXPLICIT - Java host methods or fields, must be public and be annotated with @Export to make them accessible to the guest language.

https://www.graalvm.org/truffle/javadoc/org/graalvm/polyglot/HostAccess.html

或者,您可以使用HostAccess.Builder进行更细粒度的控制

https://www.graalvm.org/truffle/javadoc/org/graalvm/polyglot/HostAccess.Builder.html

zpqajqem

zpqajqem2#

如果由于某些原因无法使用HostAccess.EXPLICIT(例如,您希望保持对java.util等的访问),然后您可以创建只公开相关方法的定制 Package 类。使用AllowHostClassLookup(),您可以限制在引擎中公开哪些类。

public class Example {
    public static void main(String[] args) {
        TestService service = new TestService();
        Context.Builder builder = Context.newBuilder("js")
            .allowHostAccess(HostAccess.ALL)
            .allowHostClassLookup(path -> path.endsWith("TestServiceScriptable"));
        GraalJSScriptEngine engine = GraalJSScriptEngine.create(null, builder);
        engine.put("service", TestServiceScriptable.newInstance(service));
    }

}

public class TestService {
    public void forbiddenJavaMethod() {
        System.out.println("forbidden!");
    }
    public void allowedMethod() {
        System.out.println("allowed");
    }
}

public class TestServiceScriptable {
    private final TestService service;

    private TestServiceScriptable(TestService service) {
        this.service = service;
    }

    public static TestServiceScriptable newInstance(TestService service) {
        return new TestServiceScriptable(service);
    }

    public void allowedMethod() {
        service.allowedMethod();
    }
}

然后:

// Should work
service.allowedMethod();

// Shouldn't work
service.forbiddenMethod();

相关问题