Custom Java SecurityManager in JUnit tests are fai

2019-08-18 16:57发布

问题:

I'm using a custom Java SecurityManager for a sandboxed plugin. It works fine when running standalone but when I run my unit tests I get a bunch of AccessControlExceptions. E.g.

java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "createClassLoader") at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
    at java.security.AccessController.checkPermission(AccessController.java:884)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
    at java.lang.SecurityManager.checkCreateClassLoader(SecurityManager.java:611)
    at java.lang.ClassLoader.checkCreateClassLoader(ClassLoader.java:274)
    at java.lang.ClassLoader.<init>(ClassLoader.java:316)
    at java.security.SecureClassLoader.<init>(SecureClassLoader.java:76)

And here's the custom SecurityManager:

    Policy.setPolicy(new Policy() {
        @Override
        public PermissionCollection getPermissions(CodeSource cs) {
            Permissions mainPermissions = new Permissions();
            mainPermissions.add(new AllPermission());
            return mainPermissions;
        }
    });
    // set a security manager so permissions get applied,
    System.setSecurityManager(new SecurityManager());

回答1:

Well...

It turns out the problem has nothing to do with JUnit. It was merely a side effect of how my tests were run. Also, there is more than one problem. I don't completely understand this but I do have a solution.

Problem 1

In Logback's Loader there's some code to check RuntimePermission for "getClassLoader". This generates an exception but is expected apparently and was confusing me. The code will continue after this exception just fine (I had a break point in the Security Manager as well as security debug turned on and thought this was the issue).

Problem 2

https://bugs.openjdk.java.net/browse/JDK-8143638

There's some kind of interaction with the fork join pool and parallel streams that was causing another security problem for me. I was using a CompletableFuture without specifying my own executor. Adding my own executor solved the problem. Honestly, I'm not sure why even after reading that bug and the linked-to documentation.



标签: java junit