views:

444

answers:

2

I'm developing a system that allows developers to upload custom groovy scripts and freemarker templates.

I can provide a certain level of security at a very high level with the default Java security infrastructure - i.e. prevent code from accessing the filesystem or network, however I have a need to restrict access to specific methods.

My plan was to modify the Groovy and Freemarker runtimes to read Annotations that would either whitelist or blacklist certain methods, however this would force me to maintain a forked version of their code, which is not desirable.

All I essentially need to be able to do is prevent the execution of specific methods when called from Groovy or Freemarker. I've considered a hack that would look at the call stack, but this would be a massive speed hit (and it quite messy).

Does anyone have any other ideas for implementing this?

+1  A: 

OSGi is great for this. You can partition your code into bundles and set exactly what each bundle exposes, and to what other bundles. Would that work for you?

dj_segfault
Does this allow me to restrict code from calling specific methods?
Zoomzoom83
The concept is something like bundling. You can then restrict methods and stuff outside that bundle.
Adeel Ansari
Strictly speaking, you can't restrict certain methods of a class from being called, but you could create a base class and child class with more methods, and only give access to the more-restrictive base class.
dj_segfault
+2  A: 

You can do it by subclassing the GroovyClassLoader and enforcing your constraints within an AST Visitor. THis post explains how to do it: http://hamletdarcy.blogspot.com/2009/01/groovy-compile-time-meta-magic.html

Also, the code referenced there is in the samples folder of Groovy 1.6 installer.

Hamlet D'Arcy
In many (most) cases the class the method is on won't be known at compile time, so analazying the AST won't really work. Still, this is the best answer here so I'll tick this one.I ended finding a decent solution using Metaclasses.
Zoomzoom83