Groovy is a very cool dynamic language for the JVM. Because it runs on the JVM, it also has the great security features as well.
Let's see how we can run trusted code and allow a dynamic (possibly user defined) script to execute with limited permissions. We will also see how the script can call functions in our trusted code and how we can elevate privileges to allow the untrusted script to get access to trusted data.
Setting up a security policy
We are going to create a java policy file that gives our script and groovy full access, but no permissions for our untrusted scripts
Now we are going to create our Trusted script, which will evaluate our untrusted script in a sandbox.
We specify the code base to assign to the script, which will inherit the permissions in our security policy.
We also pass in our class into the script's binding, allowing it to call our methods. This let's us specify an API for the script to use to access trusted data, which we control access to.
By using AccessController.doPrivileged(), we can elevate our privileges to that of the calling code base.
This code is executed in a sandbox, with permissions defined in our security policy. You can see that if we try to do something we don't have permission for, access is denied.
By calling our trusted class, which has all permissions, we can give the script access to certain things, but we control it.