如何在 kotlin 协程中执行特权?

问题描述

在 Java 中,我可以通过调用 java.security.AccessController.doPrivileged() 来提升权限。

如何在 kotlin 协程中提升权限?

示例:当我调用程序时

import java.security.AccessControlContext
import java.security.AccessController
import java.security.PrivilegedAction
import java.security.ProtectionDomain
import kotlinx.coroutines.runBlocking

object Privileged {

  private fun checkDirect(expectAllowed: Boolean) {
    try {
      System.getProperty("allowed")
      if (expectAllowed) {
        println("expected: allowed")
      }
      else {
        println("UNEXPECTED: allowed")
      }
    } catch (e: SecurityException) {
      if (expectAllowed) {
        println("UNEXPECTED: forbidden")
      }
      else {
        println("expected: forbidden")
      }
    }
  }

  private suspend fun checkSuspend(expectAllowed: Boolean) {
    checkDirect(expectAllowed)
  }

  @JvmStatic
  fun main(vararg argv: String) {
    // drop privileges
    AccessController.doPrivileged(
      PrivilegedAction {
        // privileges are all dropped here

        // 1. direct functions:

        // this check will fail
        checkDirect(false)

        // raise privilege
        AccessController.doPrivileged(
          PrivilegedAction {
            // privileges are all raised here
            // so this check will succeed
            checkDirect(true)
          }
        )

        // 2. suspend functions:

        runBlocking {
          // this call will fail
          checkSuspend(false)

          // FIXME: How to call checkSuspend(true) with raised privileges?
        }
      },AccessControlContext(arrayOf(ProtectionDomain(null,null)))
    )
  }
}

使用 java -Djava.security.manager -Djava.security.policy=java.policy Privileged,其中 java.policy 是

grant {
  permission java.security.AllPermission;
};

我明白

expected: forbidden
expected: allowed
expected: forbidden

调用具有提升权限的 checkSuspend 的 AccessController.doPrivileged() 等价物是什么(请参阅程序代码中的 FIXME)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...