What am I trying to achieve?
I am working on a Java application that can be supplemented with additional banks that integrate through ServiceLoader. These downloaded extensions should run with some SecurityManager limitations, of course, just to increase security. As an example, each Extension should receive one specific directory where it can store everything, but access to any other file / folder should be limited. The main application is trusted code and therefore can work without any restrictions. In addition, the main application provides some api implementations for each extension, which should also run without restriction. This means that the extension should not access the file outside its directory, but when the extension calls the api method, which tries to access any other file,Access must be granted.
Question
How can I achieve the mentioned behavior, which is limited only to โdirectโ calls from extension classes, but is not code from the main application? Running extensions on different threads / threadGroups may be a good solution anyway, but since api calls can be performed under the same thread (group), this may not help determine whether access should be restricted or not based only on thread.
Example
I created a simplified test environment. On the one hand, these two interfaces:
public interface Extension {
void doSomethingRestricted();
void doSameViaApi(ExtensionApi api);
}
public interface ExtensionApi {
void doSomethingWithHigherPermissions();
}
For testing, I created a jar containing this extension:
public class SomeExtension implements Extension {
public void doSomethingRestricted() {
System.out.println(System.getProperty("user.home"));
}
public void doSameViaApi(final ExtensionApi api) {
api.doSomethingWithHigherPermissions();
}
}
In the main application, I would like to do something like this:
final ExtensionApi api = () -> System.out.println(System.getProperty("user.home"));
try {
final URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
for(final Extension extension : ServiceLoader.load(Extension.class, urlClassLoader)) {
extension.doSomethingRestricted();
extension.doSameViaApi(api);
}
}
, extension.doSomethingRestricted();
, SecurityException, extension.doSameViaApi(api);
.
, , api. , , - , , . , , , , , ?