Sandboxing JavaScript in Java App – Link Collection
The JVM is by design an insecure environment and it is generally difficult to run untrusted code in a sandboxed environment.
However, it seems that is relatively easy to sandbox JavaScript code running in Oracle Nashorn. The instructions are here. Strangely, this was not easy to find through a Google search.
Below I have listed some further sources on Sandboxing JavaScript and Java code. Although there is plenty of material on Rhino, I would not recommend using this engine. I think Nashorn has been designed with support for Sandboxed code in mind from the very beginning while in Rhino the functionality feels kind of bolted on.
UPDATE I have implemented two little libraries which takes care of the grunt work of sandboxing Nashorn and Rhino code in Java:
Nashorn Sandbox (on GitHub)
Rhino Sandbox (on Github)
Sandboxing JavaScript
Nashorn
Restricting Script Access to Specified Java Classes: From the Oracle Nashorn docs. Shows how to restrict access to specific Java classes.
Rhino
Class ContextFactory: Useful for monitoring and setting restrictions on Rhino code.
Method initSafeStandardObjects: Useful for creating sandboxed Rhino code.
Rhino Sandbox: A small library for sandboxing JavaScript code running in Rhino.
Sandboxing Rhino in Java: Blog post
Securing Rhino in Java6: Blog post
DynJS
Sandboxing JavaScript Execution in Java: Blog post
Sandboxing Java
Example Code Monitoring Threads: Example code how thread CPU usage can be monitored.
The Java Sandbox: A library for sandboxing any Java code. Might be useful to sandbox the Java code with runs the script.