Restricting allowed types in Kotlin Script Engine (JSR-223)

In Nashorn engine we can do the following to selectively allow only for restricted set of classes which can be used inside of scripts:

val factory = NashornScriptEngineFactory()
val engine = factory.getScriptEngine(object : ClassFilter {
	override fun exposeToScripts(className: String): Boolean = when (className) {
		File::class.java.name -> false
		else -> true
	}
})

try {
	engine.eval("""
		var File = Java.type("java.io.File");
		var file = new File("\\")
	""")
} catch (e: RuntimeException) {
	System.err.println(e.message) // java.lang.ClassNotFoundException: java.io.File
}

This approach can be used to create and use sandboxed scripts without exposing any unnecessary Java classes.

The question now is wherever something similar can be achieved in Kotlin Script Engine?

You could go with the solution of using a custom classloader to instantiate the script engine, but then you would need to make sure that the types used by then engine itself (and any jitted classes) would be allowed. Of course for restricting file access you’d also want to use java security permissions.

Well, after some experimenting I came to conclusion that the best method would be just to define the appropriate policy rules for Security Manager. This alone will prevent scripts from accessing file system or making socket connections.

Do you have an example of how you restricted these classes?