JUnit测试中的自定义Java SecurityManager失败 [英] Custom Java SecurityManager in JUnit tests are failing

查看:260
本文介绍了JUnit测试中的自定义Java SecurityManager失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为沙盒插件使用自定义Java SecurityManager.当独立运行时,它工作正常,但是当我运行单元测试时,我得到了一堆AccessControlException.例如

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)

这是自定义的SecurityManager:

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());

推荐答案

好吧...

事实证明,该问题与JUnit无关.这只是我的测试运行方式的副作用.而且,存在多个问题.我不完全了解这一点,但确实有解决方案.

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.

问题1

在Logback的Loader中,有一些代码可以检查RuntimePermission中的"getClassLoader".这产生了一个异常,但显然是预期的,这使我感到困惑.该异常发生后,代码将继续运行(我在安全管理器中有一个断点,并且打开了安全调试,并认为这是问题所在.)

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).

问题2

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

与fork联接池和并行流进行某种交互,这对我造成了另一个安全问题.我在使用CompletableFuture时未指定自己的执行程序.添加我自己的执行程序可以解决该问题.老实说,即使在阅读了该错误和链接的文档之后,我也不确定为什么.

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.

这篇关于JUnit测试中的自定义Java SecurityManager失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆