pan3793 commented on code in PR #7437:
URL: https://github.com/apache/kyuubi/pull/7437#discussion_r4596899772


##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala
+      .filter { case (key, _) =>
+        CONFIG_PREFIXES.exists(key.startsWith) && !isAdminOnlyKey(key)
+      }
+      .foreach { case (key, value) => props.put(key, value) }
+    // The Ranger authorizer factory defaults to the embedded authorizer, but 
the
+    // plugin default is the Ranger PDP remote authorizer. Set it explicitly 
when
+    // the configuration does not select an implementation.
+    if (!props.containsKey(KEY_IMPL_CLASS)) {
+      props.put(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    }
+    validateAdminOnlyKeys(props)
+    initialize(props)
+  }
+
+  private[ranger] def isAdminOnlyKey(key: String): Boolean =
+    ADMIN_ONLY_KEYS.contains(key) || 
ADMIN_ONLY_KEY_PREFIXES.exists(key.startsWith)
+
+  /**
+   * Fails fast when the Ranger configuration resources lack a configuration 
the
+   * authorizer needs: the authorizer implementation defaults to the Ranger 
PDP mode,
+   * which requires the Ranger PDP server address. The configuration cannot 
fall back
+   * to JVM system properties, which tenant users may control.
+   */
+  private def validateAdminOnlyKeys(props: Properties): Unit = {
+    val implClass = props.getProperty(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    if (implClass == REMOTE_AUTHORIZER_CLASS && props.getProperty(KEY_PDP_URL) 
== null) {
+      throw new IllegalArgumentException(
+        s"$KEY_PDP_URL must be configured in ${CONFIG_RESOURCES.mkString(", 
")} and " +
+          "cannot be set by JVM system properties")
+    }
+  }
+
+  private def ensureConfig(): Unit = {
+    if (config == null) {
+      config = new Configuration
+      CONFIG_RESOURCES.foreach(addResourceIfReadable)
+    }
+  }
+
+  private def addResourceIfReadable(resource: String): Unit = {
+    val loader = Thread.currentThread().getContextClassLoader
+    val url = if (loader != null) loader.getResource(resource) else null
+    if (url != null) {
+      config.addResource(url)
+    } else {
+      config.addResource(resource)
+    }
   }
 
+  private[ranger] def initialize(props: Properties): Unit = synchronized {
+    if (authorizer == null) {
+      props.put("ranger.authz.app.type", APP_TYPE)
+      authorizer = RangerAuthorizerFactory.createAuthorizer(props)
+      authorizer.init()
+      registerCleanupShutdownHook(authorizer)
+      LOG.info(
+        s"initialized ranger authorizer, service: $serviceName, " +
+          s"impl: ${authorizer.getClass.getName}")
+    }
+  }
+
+  private[ranger] def authorizerClassName: String =
+    if (authorizer == null) null else authorizer.getClass.getName
+
   /**
-   * register shutdown hook for plugin cleanup
+   * Reset the authorizer to the uninitialized state, so that the next
+   * [[initialize]] call re-creates it. Intended for tests only.
    */
-  private def registerCleanupShutdownHook(plugin: RangerBasePlugin): Unit = {
+  private[ranger] def reset(): Unit = synchronized {
+    if (authorizer != null) {
+      try authorizer.close()
+      catch {
+        case e: Exception => LOG.warn("failed to close ranger authorizer", e)
+      }
+      authorizer = null
+    }
+  }
+
+  private def registerCleanupShutdownHook(authorizer: RangerAuthorizer): Unit 
= {
     ShutdownHookManager.get().addShutdownHook(
       () => {
-        if (plugin != null) {
-          LOG.info(s"clean up ranger plugin, appId: ${plugin.getAppId}")
-          plugin.cleanup()
-          plugin.getAuditProviderFactory.shutdown()
+        if (authorizer != null) {
+          LOG.info(s"clean up ranger authorizer, impl: 
${authorizer.getClass.getName}")
+          try authorizer.close()
+          catch {
+            case e: Exception => LOG.warn("failed to close ranger authorizer", 
e)
+          }
         }
       },
       Integer.MAX_VALUE)
   }
 
+  private def checkInitialized(): RangerAuthorizer = {
+    if (authorizer == null) {
+      initialize()
+    }
+    authorizer
+  }
+
+  private def userInfo(req: AccessRequest): RangerUserInfo =
+    new RangerUserInfo(req.user, null, req.userGroups.asJava, null)
+
+  private def permissionOf(accessType: AccessType): String = accessType match {
+    // the Ranger any-access marker (RangerPolicyEngine.ANY_ACCESS) allows any 
access
+    // type matched by policies, e.g. for SHOW commands
+    case USE => "_any"
+    case _ => accessType.toString.toLowerCase
+  }
+
+  private def context(): RangerAccessContext = {
+    val additionalInfo = new java.util.HashMap[String, AnyRef]
+    val clusterName = config.get(KEY_CLUSTER_NAME)
+    if (clusterName != null) {
+      additionalInfo.put(CONTEXT_INFO_CLUSTER_NAME, clusterName)
+    }
+    val ctx = new RangerAccessContext(SERVICE_TYPE, serviceName)
+    ctx.setAccessTime(System.currentTimeMillis)
+    ctx.setAdditionalInfo(additionalInfo)
+    ctx
+  }
+
+  private def toAuthzRequest(
+      req: AccessRequest,
+      resourceInfo: RangerResourceInfo): RangerAuthzRequest = {
+    val access = new RangerAccessInfo(
+      resourceInfo,
+      req.opType.toString,
+      java.util.Collections.singleton(permissionOf(req.accessType)))
+    new RangerAuthzRequest(userInfo(req), access, context())
+  }
+
+  private def toAuthzRequest(req: AccessRequest): RangerAuthzRequest =
+    toAuthzRequest(req, req.resource.toResourceInfos.head)
+
+  /**
+   * batch verifying RangerAccessRequests
+   * and throws exception with all disallowed privileges
+   * for accessType and resources
+   */
+  def verify(requests: Seq[AccessRequest]): Unit = {
+    if (requests.nonEmpty) {
+      val authorizer = checkInitialized()
+      val user = userInfo(requests.head)
+      val ctx = context()
+      // a uri resource has two variants, the exact path and the path with a 
trailing
+      // slash, which are authorized as alternatives by separate requests; the 
single
+      // call authorizes a fixed set of accesses conjunctively, so it is used 
only when
+      // the requests contain no uri resource
+      val hasUri = requests.exists(_.resource.objectType == ObjectType.URI)
+      val results = if (authorizeInSingleCall && !hasUri) {
+        val accesses = requests.map(toAuthzRequest(_).getAccess).asJava
+        (for {
+          multiResult <-
+            Option(authorizer.authorize(new RangerMultiAuthzRequest(user, 
accesses, ctx)))
+          accessResults <- Option(multiResult.getAccesses)
+        } yield 
accessResults.asScala.map(Option(_)).toSeq).getOrElse(Seq.empty)
+      } else {
+        requests.map { req =>
+          val variantResults = req.resource.toResourceInfos.map { resourceInfo 
=>
+            Option(authorizer.authorize(toAuthzRequest(req, resourceInfo)))
+          }
+          variantResults.find(_.exists(_.getDecision == AccessDecision.ALLOW))
+            .getOrElse(variantResults.head)
+        }
+      }
+
+      // a missing result means the authorizer could not evaluate the request,
+      // which is denied instead of skipped
+      val indices = results.padTo(requests.length, None).zipWithIndex.collect {
+        case (result, idx) if result.forall(_.getDecision != 
AccessDecision.ALLOW) => idx
+      }
+      if (indices.nonEmpty) {
+        val accessTypeToResource =
+          indices.foldLeft(LinkedHashMap.empty[String, 
ArrayBuffer[String]])((m, idx) => {
+            val req = requests(idx)
+            val accessType = permissionOf(req.accessType)
+            val resource = req.resource.getAsString
+            m.getOrElseUpdate(accessType, ArrayBuffer.empty[String])
+              .append(resource)
+            m
+          })
+        val errorMsg = accessTypeToResource
+          .map { case (accessType, resources) =>
+            s"[$accessType] ${resources.mkString("privilege on [", ",", "]")}"
+          }.mkString(", ")
+        throw new AccessControlException(
+          s"Permission denied: user [${requests.head.user}] does not have 
$errorMsg")
+      }
+    }
+  }
+
+  private def requireResult(result: RangerAuthzResult, req: AccessRequest): 
RangerAuthzResult =
+    if (result == null) {
+      // a missing result means the authorizer could not evaluate the request,
+      // which must not be treated as allowed
+      throw new AccessControlException(
+        s"Permission denied: no authorization result for user [${req.user}], " 
+
+          s"resource [${req.resource.getAsString}]")
+    } else {
+      result
+    }
+
   def getFilterExpr(req: AccessRequest): Option[String] = {
-    val result = evalRowFilterPolicies(req, null)
+    val result = 
requireResult(checkInitialized().authorize(toAuthzRequest(req)), req)
     Option(result)
-      .filter(_.isRowFilterEnabled)
+      .filter(_.getDecision == AccessDecision.ALLOW)

Review Comment:
   This drops the row filter whenever the table-level `select` decision is not 
ALLOW. With a column-only grant (e.g. select on `default.src` column `key`), 
Ranger skips the column policy for a table-level request (DESCENDANT match, 
non-any access type in `RangerDefaultPolicyEvaluator`). The decision is then 
NOT_DETERMINED, but `RangerAuthzPlugin.evaluate` still fills in the row filter. 
`verify` allows column `key`, and the user reads every row unfiltered. The 
plugin on master applied `evalRowFilterPolicies` whatever the access decision 
was.
   
   Ranger already clears the row filter and data mask on DENY 
(`RangerAuthzPlugin.authorize`). Please drop the decision filter here and at 
L360, and add a test with a column-only grant plus a row filter.



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala
+      .filter { case (key, _) =>
+        CONFIG_PREFIXES.exists(key.startsWith) && !isAdminOnlyKey(key)
+      }
+      .foreach { case (key, value) => props.put(key, value) }
+    // The Ranger authorizer factory defaults to the embedded authorizer, but 
the
+    // plugin default is the Ranger PDP remote authorizer. Set it explicitly 
when
+    // the configuration does not select an implementation.
+    if (!props.containsKey(KEY_IMPL_CLASS)) {
+      props.put(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    }
+    validateAdminOnlyKeys(props)
+    initialize(props)
+  }
+
+  private[ranger] def isAdminOnlyKey(key: String): Boolean =
+    ADMIN_ONLY_KEYS.contains(key) || 
ADMIN_ONLY_KEY_PREFIXES.exists(key.startsWith)
+
+  /**
+   * Fails fast when the Ranger configuration resources lack a configuration 
the
+   * authorizer needs: the authorizer implementation defaults to the Ranger 
PDP mode,
+   * which requires the Ranger PDP server address. The configuration cannot 
fall back
+   * to JVM system properties, which tenant users may control.
+   */
+  private def validateAdminOnlyKeys(props: Properties): Unit = {
+    val implClass = props.getProperty(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    if (implClass == REMOTE_AUTHORIZER_CLASS && props.getProperty(KEY_PDP_URL) 
== null) {
+      throw new IllegalArgumentException(
+        s"$KEY_PDP_URL must be configured in ${CONFIG_RESOURCES.mkString(", 
")} and " +
+          "cannot be set by JVM system properties")
+    }
+  }
+
+  private def ensureConfig(): Unit = {
+    if (config == null) {
+      config = new Configuration
+      CONFIG_RESOURCES.foreach(addResourceIfReadable)
+    }
+  }
+
+  private def addResourceIfReadable(resource: String): Unit = {
+    val loader = Thread.currentThread().getContextClassLoader
+    val url = if (loader != null) loader.getResource(resource) else null
+    if (url != null) {
+      config.addResource(url)
+    } else {
+      config.addResource(resource)
+    }
   }
 
+  private[ranger] def initialize(props: Properties): Unit = synchronized {
+    if (authorizer == null) {
+      props.put("ranger.authz.app.type", APP_TYPE)
+      authorizer = RangerAuthorizerFactory.createAuthorizer(props)
+      authorizer.init()
+      registerCleanupShutdownHook(authorizer)
+      LOG.info(
+        s"initialized ranger authorizer, service: $serviceName, " +
+          s"impl: ${authorizer.getClass.getName}")
+    }
+  }
+
+  private[ranger] def authorizerClassName: String =
+    if (authorizer == null) null else authorizer.getClass.getName
+
   /**
-   * register shutdown hook for plugin cleanup
+   * Reset the authorizer to the uninitialized state, so that the next
+   * [[initialize]] call re-creates it. Intended for tests only.
    */
-  private def registerCleanupShutdownHook(plugin: RangerBasePlugin): Unit = {
+  private[ranger] def reset(): Unit = synchronized {
+    if (authorizer != null) {
+      try authorizer.close()
+      catch {
+        case e: Exception => LOG.warn("failed to close ranger authorizer", e)
+      }
+      authorizer = null
+    }
+  }
+
+  private def registerCleanupShutdownHook(authorizer: RangerAuthorizer): Unit 
= {
     ShutdownHookManager.get().addShutdownHook(
       () => {
-        if (plugin != null) {
-          LOG.info(s"clean up ranger plugin, appId: ${plugin.getAppId}")
-          plugin.cleanup()
-          plugin.getAuditProviderFactory.shutdown()
+        if (authorizer != null) {
+          LOG.info(s"clean up ranger authorizer, impl: 
${authorizer.getClass.getName}")
+          try authorizer.close()
+          catch {
+            case e: Exception => LOG.warn("failed to close ranger authorizer", 
e)
+          }
         }
       },
       Integer.MAX_VALUE)
   }
 
+  private def checkInitialized(): RangerAuthorizer = {
+    if (authorizer == null) {
+      initialize()
+    }
+    authorizer
+  }
+
+  private def userInfo(req: AccessRequest): RangerUserInfo =
+    new RangerUserInfo(req.user, null, req.userGroups.asJava, null)
+
+  private def permissionOf(accessType: AccessType): String = accessType match {
+    // the Ranger any-access marker (RangerPolicyEngine.ANY_ACCESS) allows any 
access
+    // type matched by policies, e.g. for SHOW commands
+    case USE => "_any"
+    case _ => accessType.toString.toLowerCase
+  }
+
+  private def context(): RangerAccessContext = {
+    val additionalInfo = new java.util.HashMap[String, AnyRef]
+    val clusterName = config.get(KEY_CLUSTER_NAME)
+    if (clusterName != null) {
+      additionalInfo.put(CONTEXT_INFO_CLUSTER_NAME, clusterName)
+    }
+    val ctx = new RangerAccessContext(SERVICE_TYPE, serviceName)
+    ctx.setAccessTime(System.currentTimeMillis)
+    ctx.setAdditionalInfo(additionalInfo)
+    ctx
+  }
+
+  private def toAuthzRequest(
+      req: AccessRequest,
+      resourceInfo: RangerResourceInfo): RangerAuthzRequest = {
+    val access = new RangerAccessInfo(
+      resourceInfo,
+      req.opType.toString,
+      java.util.Collections.singleton(permissionOf(req.accessType)))
+    new RangerAuthzRequest(userInfo(req), access, context())
+  }
+
+  private def toAuthzRequest(req: AccessRequest): RangerAuthzRequest =
+    toAuthzRequest(req, req.resource.toResourceInfos.head)
+
+  /**
+   * batch verifying RangerAccessRequests
+   * and throws exception with all disallowed privileges
+   * for accessType and resources
+   */
+  def verify(requests: Seq[AccessRequest]): Unit = {
+    if (requests.nonEmpty) {
+      val authorizer = checkInitialized()
+      val user = userInfo(requests.head)
+      val ctx = context()
+      // a uri resource has two variants, the exact path and the path with a 
trailing
+      // slash, which are authorized as alternatives by separate requests; the 
single
+      // call authorizes a fixed set of accesses conjunctively, so it is used 
only when
+      // the requests contain no uri resource
+      val hasUri = requests.exists(_.resource.objectType == ObjectType.URI)
+      val results = if (authorizeInSingleCall && !hasUri) {
+        val accesses = requests.map(toAuthzRequest(_).getAccess).asJava
+        (for {
+          multiResult <-
+            Option(authorizer.authorize(new RangerMultiAuthzRequest(user, 
accesses, ctx)))
+          accessResults <- Option(multiResult.getAccesses)
+        } yield 
accessResults.asScala.map(Option(_)).toSeq).getOrElse(Seq.empty)
+      } else {
+        requests.map { req =>
+          val variantResults = req.resource.toResourceInfos.map { resourceInfo 
=>
+            Option(authorizer.authorize(toAuthzRequest(req, resourceInfo)))
+          }
+          variantResults.find(_.exists(_.getDecision == AccessDecision.ALLOW))
+            .getOrElse(variantResults.head)
+        }
+      }
+
+      // a missing result means the authorizer could not evaluate the request,
+      // which is denied instead of skipped
+      val indices = results.padTo(requests.length, None).zipWithIndex.collect {
+        case (result, idx) if result.forall(_.getDecision != 
AccessDecision.ALLOW) => idx
+      }
+      if (indices.nonEmpty) {
+        val accessTypeToResource =
+          indices.foldLeft(LinkedHashMap.empty[String, 
ArrayBuffer[String]])((m, idx) => {
+            val req = requests(idx)
+            val accessType = permissionOf(req.accessType)
+            val resource = req.resource.getAsString
+            m.getOrElseUpdate(accessType, ArrayBuffer.empty[String])
+              .append(resource)
+            m
+          })
+        val errorMsg = accessTypeToResource
+          .map { case (accessType, resources) =>
+            s"[$accessType] ${resources.mkString("privilege on [", ",", "]")}"
+          }.mkString(", ")
+        throw new AccessControlException(
+          s"Permission denied: user [${requests.head.user}] does not have 
$errorMsg")
+      }
+    }
+  }
+
+  private def requireResult(result: RangerAuthzResult, req: AccessRequest): 
RangerAuthzResult =
+    if (result == null) {
+      // a missing result means the authorizer could not evaluate the request,
+      // which must not be treated as allowed
+      throw new AccessControlException(
+        s"Permission denied: no authorization result for user [${req.user}], " 
+
+          s"resource [${req.resource.getAsString}]")
+    } else {
+      result
+    }
+
   def getFilterExpr(req: AccessRequest): Option[String] = {
-    val result = evalRowFilterPolicies(req, null)
+    val result = 
requireResult(checkInitialized().authorize(toAuthzRequest(req)), req)
     Option(result)
-      .filter(_.isRowFilterEnabled)
+      .filter(_.getDecision == AccessDecision.ALLOW)
+      .flatMap { r =>
+        Option(r.getPermissions.get(permissionOf(req.accessType)))
+      }
+      .map(_.getRowFilter)
+      .filter(rf => rf != null && rf.getFilterExpr != null && 
rf.getFilterExpr.nonEmpty)
       .map(_.getFilterExpr)
-      .filter(fe => fe != null && fe.nonEmpty)
   }
 
   def getMaskingExpr(req: AccessRequest): Option[String] = {
-    val col = req.getResource.asInstanceOf[AccessResource].getColumn
-    val result = evalDataMaskPolicies(req, null)
-    Option(result).filter(_.isMaskEnabled).map { res =>
-      if ("MASK_NULL".equalsIgnoreCase(res.getMaskType)) {
-        "NULL"
-      } else if ("CUSTOM".equalsIgnoreCase(result.getMaskType)) {
-        val maskVal = res.getMaskedValue
-        if (maskVal == null) {
+    val col = req.resource.getColumn
+    val result = 
requireResult(checkInitialized().authorize(toAuthzRequest(req)), req)
+    Option(result)
+      .filter(_.getDecision == AccessDecision.ALLOW)
+      .flatMap { r =>
+        Option(r.getPermissions.get(permissionOf(req.accessType)))
+      }
+      .map(_.getDataMask)
+      .filter(dm => dm != null && dm.getMaskType != null)
+      .map { dm =>
+        val maskType = dm.getMaskType
+        if ("MASK_NULL".equalsIgnoreCase(maskType)) {
           "NULL"
+        } else if ("CUSTOM".equalsIgnoreCase(maskType)) {
+          val maskVal = dm.getMaskedValue
+          if (maskVal == null) {
+            "NULL"
+          } else {
+            s"${maskVal.replace("{col}", col)}"
+          }
         } else {
-          s"${maskVal.replace("{col}", col)}"
-        }
-      } else if (result.getMaskTypeDef != null) {
-        result.getMaskTypeDef.getName match {
-          case "MASK" => regexp_replace(col)
-          case "MASK_SHOW_FIRST_4" =>
-            regexp_replace(col, hasLen = true)
-          case "MASK_SHOW_LAST_4" =>
-            val left = regexp_replace(s"left($col, length($col) - 4)")
-            s"concat($left, right($col, 4))"
-          case "MASK_HASH" => s"md5(cast($col as string))"
-          case "MASK_DATE_SHOW_YEAR" => s"date_trunc('YEAR', $col)"
-          case _ => result.getMaskTypeDef.getTransformer match {
-              case transformer if transformer != null && transformer.nonEmpty 
=>
-                s"${transformer.replace("{col}", col)}"
-              case _ => null
-            }
+          maskType match {
+            case "MASK" => regexp_replace(col)
+            case "MASK_SHOW_FIRST_4" =>
+              regexp_replace(col, hasLen = true)
+            case "MASK_SHOW_LAST_4" =>
+              val left = regexp_replace(s"left($col, length($col) - 4)")
+              s"concat($left, right($col, 4))"
+            case "MASK_HASH" => s"md5(cast($col as string))"
+            case "MASK_DATE_SHOW_YEAR" => s"date_trunc('YEAR', $col)"
+            case _ => Option(dm.getMaskedValue)
+                .filter(_.nonEmpty)
+                .map(maskedValue => s"${maskedValue.replace("{col}", col)}")
+                .orNull

Review Comment:
   `getMaskedValue` is only set from the policy item's `valueExpr` 
(`RangerDefaultDataMaskPolicyItemEvaluator`), which in practice means CUSTOM 
masks. Any other mask type, e.g. one added to the service def's `dataMaskDef` 
with a transformer, now leaves the column unmasked. The plugin on master fell 
back to `getMaskTypeDef.getTransformer`, which the authz API result no longer 
carries. Please fail closed:
   
   ```suggestion
               case _ => Option(dm.getMaskedValue)
                   .filter(_.nonEmpty)
                   .map(maskedValue => s"${maskedValue.replace("{col}", col)}")
                   .getOrElse("NULL")
   ```



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala
+      .filter { case (key, _) =>
+        CONFIG_PREFIXES.exists(key.startsWith) && !isAdminOnlyKey(key)
+      }
+      .foreach { case (key, value) => props.put(key, value) }
+    // The Ranger authorizer factory defaults to the embedded authorizer, but 
the
+    // plugin default is the Ranger PDP remote authorizer. Set it explicitly 
when
+    // the configuration does not select an implementation.
+    if (!props.containsKey(KEY_IMPL_CLASS)) {
+      props.put(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    }
+    validateAdminOnlyKeys(props)
+    initialize(props)
+  }
+
+  private[ranger] def isAdminOnlyKey(key: String): Boolean =
+    ADMIN_ONLY_KEYS.contains(key) || 
ADMIN_ONLY_KEY_PREFIXES.exists(key.startsWith)
+
+  /**
+   * Fails fast when the Ranger configuration resources lack a configuration 
the
+   * authorizer needs: the authorizer implementation defaults to the Ranger 
PDP mode,
+   * which requires the Ranger PDP server address. The configuration cannot 
fall back
+   * to JVM system properties, which tenant users may control.
+   */
+  private def validateAdminOnlyKeys(props: Properties): Unit = {
+    val implClass = props.getProperty(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    if (implClass == REMOTE_AUTHORIZER_CLASS && props.getProperty(KEY_PDP_URL) 
== null) {
+      throw new IllegalArgumentException(
+        s"$KEY_PDP_URL must be configured in ${CONFIG_RESOURCES.mkString(", 
")} and " +
+          "cannot be set by JVM system properties")
+    }
+  }
+
+  private def ensureConfig(): Unit = {
+    if (config == null) {
+      config = new Configuration
+      CONFIG_RESOURCES.foreach(addResourceIfReadable)
+    }
+  }
+
+  private def addResourceIfReadable(resource: String): Unit = {
+    val loader = Thread.currentThread().getContextClassLoader
+    val url = if (loader != null) loader.getResource(resource) else null
+    if (url != null) {
+      config.addResource(url)
+    } else {
+      config.addResource(resource)
+    }
   }
 
+  private[ranger] def initialize(props: Properties): Unit = synchronized {
+    if (authorizer == null) {
+      props.put("ranger.authz.app.type", APP_TYPE)
+      authorizer = RangerAuthorizerFactory.createAuthorizer(props)
+      authorizer.init()
+      registerCleanupShutdownHook(authorizer)
+      LOG.info(
+        s"initialized ranger authorizer, service: $serviceName, " +
+          s"impl: ${authorizer.getClass.getName}")
+    }
+  }
+
+  private[ranger] def authorizerClassName: String =
+    if (authorizer == null) null else authorizer.getClass.getName
+
   /**
-   * register shutdown hook for plugin cleanup
+   * Reset the authorizer to the uninitialized state, so that the next
+   * [[initialize]] call re-creates it. Intended for tests only.
    */
-  private def registerCleanupShutdownHook(plugin: RangerBasePlugin): Unit = {
+  private[ranger] def reset(): Unit = synchronized {
+    if (authorizer != null) {
+      try authorizer.close()
+      catch {
+        case e: Exception => LOG.warn("failed to close ranger authorizer", e)
+      }
+      authorizer = null
+    }
+  }
+
+  private def registerCleanupShutdownHook(authorizer: RangerAuthorizer): Unit 
= {
     ShutdownHookManager.get().addShutdownHook(
       () => {
-        if (plugin != null) {
-          LOG.info(s"clean up ranger plugin, appId: ${plugin.getAppId}")
-          plugin.cleanup()
-          plugin.getAuditProviderFactory.shutdown()
+        if (authorizer != null) {
+          LOG.info(s"clean up ranger authorizer, impl: 
${authorizer.getClass.getName}")
+          try authorizer.close()
+          catch {
+            case e: Exception => LOG.warn("failed to close ranger authorizer", 
e)
+          }
         }
       },
       Integer.MAX_VALUE)
   }
 
+  private def checkInitialized(): RangerAuthorizer = {
+    if (authorizer == null) {
+      initialize()
+    }
+    authorizer
+  }
+
+  private def userInfo(req: AccessRequest): RangerUserInfo =
+    new RangerUserInfo(req.user, null, req.userGroups.asJava, null)
+
+  private def permissionOf(accessType: AccessType): String = accessType match {
+    // the Ranger any-access marker (RangerPolicyEngine.ANY_ACCESS) allows any 
access
+    // type matched by policies, e.g. for SHOW commands
+    case USE => "_any"
+    case _ => accessType.toString.toLowerCase
+  }
+
+  private def context(): RangerAccessContext = {
+    val additionalInfo = new java.util.HashMap[String, AnyRef]
+    val clusterName = config.get(KEY_CLUSTER_NAME)
+    if (clusterName != null) {
+      additionalInfo.put(CONTEXT_INFO_CLUSTER_NAME, clusterName)
+    }
+    val ctx = new RangerAccessContext(SERVICE_TYPE, serviceName)
+    ctx.setAccessTime(System.currentTimeMillis)
+    ctx.setAdditionalInfo(additionalInfo)
+    ctx
+  }
+
+  private def toAuthzRequest(
+      req: AccessRequest,
+      resourceInfo: RangerResourceInfo): RangerAuthzRequest = {
+    val access = new RangerAccessInfo(
+      resourceInfo,
+      req.opType.toString,
+      java.util.Collections.singleton(permissionOf(req.accessType)))
+    new RangerAuthzRequest(userInfo(req), access, context())
+  }
+
+  private def toAuthzRequest(req: AccessRequest): RangerAuthzRequest =
+    toAuthzRequest(req, req.resource.toResourceInfos.head)
+
+  /**
+   * batch verifying RangerAccessRequests
+   * and throws exception with all disallowed privileges
+   * for accessType and resources
+   */
+  def verify(requests: Seq[AccessRequest]): Unit = {
+    if (requests.nonEmpty) {
+      val authorizer = checkInitialized()
+      val user = userInfo(requests.head)
+      val ctx = context()
+      // a uri resource has two variants, the exact path and the path with a 
trailing
+      // slash, which are authorized as alternatives by separate requests; the 
single
+      // call authorizes a fixed set of accesses conjunctively, so it is used 
only when
+      // the requests contain no uri resource
+      val hasUri = requests.exists(_.resource.objectType == ObjectType.URI)
+      val results = if (authorizeInSingleCall && !hasUri) {
+        val accesses = requests.map(toAuthzRequest(_).getAccess).asJava
+        (for {
+          multiResult <-
+            Option(authorizer.authorize(new RangerMultiAuthzRequest(user, 
accesses, ctx)))
+          accessResults <- Option(multiResult.getAccesses)
+        } yield 
accessResults.asScala.map(Option(_)).toSeq).getOrElse(Seq.empty)
+      } else {
+        requests.map { req =>
+          val variantResults = req.resource.toResourceInfos.map { resourceInfo 
=>
+            Option(authorizer.authorize(toAuthzRequest(req, resourceInfo)))
+          }
+          variantResults.find(_.exists(_.getDecision == AccessDecision.ALLOW))
+            .getOrElse(variantResults.head)

Review Comment:
   Accepting ALLOW from either path variant lets one variant bypass a deny on 
the other. With a non-recursive deny on url `/data/secret` and an allow on `*`, 
`url:/data/secret` is DENY but `url:/data/secret/` is ALLOW, so `LOAD DATA 
INPATH '/data/secret'` succeeds. The plugin on master sent both values in one 
request. `RangerDefaultResourceMatcher` matches a policy when any value 
matches, so the deny won. Please add a test for this case.
   
   ```suggestion
             variantResults.find(_.exists(_.getDecision == AccessDecision.DENY))
               .orElse(variantResults.find(_.exists(_.getDecision == 
AccessDecision.ALLOW)))
               .getOrElse(variantResults.head)
   ```



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/AccessResource.scala:
##########
@@ -18,27 +18,167 @@
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
 import java.io.File
-import java.util
 
-import scala.language.implicitConversions
+import scala.collection.JavaConverters._
 
-import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl
+import org.apache.commons.lang3.StringUtils
+import org.apache.ranger.authz.model.RangerResourceInfo
 
-import org.apache.kyuubi.plugin.spark.authz.{ObjectType, PrivilegeObject}
+import org.apache.kyuubi.plugin.spark.authz.{AccessControlException, 
ObjectType, PrivilegeObject}
 import org.apache.kyuubi.plugin.spark.authz.ObjectType._
 import org.apache.kyuubi.plugin.spark.authz.OperationType.OperationType
 
-class AccessResource private (val objectType: ObjectType, val catalog: 
Option[String])
-  extends RangerAccessResourceImpl {
-  implicit def asString(obj: Object): String = if (obj != null) 
obj.asInstanceOf[String] else null
-  def getDatabase: String = getValue("database")
-  def getUdf: String = getValue("udf")
-  def getTable: String = getValue("table")
-  def getColumn: String = getValue("column")
+/**
+ * A privilege object to authorize, which is converted to a Ranger resource
+ * (e.g. "table:default/src" or "column:default/src/id") in requests to
+ * the Ranger authorizer.
+ *
+ * @param objectType the type of the object
+ * @param database   the database name, or null if not applicable
+ * @param table      the table name, or null if not applicable
+ * @param column     the column names joined by comma, or null if not 
applicable
+ * @param udf        the function name, or null if not applicable
+ * @param uri        the uri path, or null if not applicable
+ * @param owner      the owner of the object, if any
+ * @param catalog    the catalog name, if any
+ */
+case class AccessResource private[ranger] (
+    objectType: ObjectType,
+    database: String,
+    table: String,
+    column: String,
+    udf: String,
+    uri: String,
+    owner: Option[String],
+    catalog: Option[String]) {
+
+  def getDatabase: String = database
+  def getUdf: String = udf
+  def getTable: String = table
+  def getColumn: String = column
+
   def getColumns: Seq[String] = {
-    val columnStr = getColumn
-    if (columnStr == null) Nil else columnStr.split(",").filter(_.nonEmpty)
+    if (column == null) Nil else column.split(",").filter(_.nonEmpty)
   }
+
+  def getOwnerUser: String = owner.orNull
+
+  /**
+   * The path-like representation of this resource used in error messages,
+   * e.g. "default/src" for a table, "default/src/id" for a column.
+   */
+  def getAsString: String = objectType match {
+    case COLUMN =>
+      Seq(database, table, column).filter(_ != null).mkString("/")
+    case FUNCTION =>
+      Seq(database, udf).filter(_ != null).mkString("/")
+    case URI =>
+      // the uri is matched against both the exact path and the path with a
+      // trailing slash, as the legacy plugin did
+      val path = Option(uri).map(_.stripSuffix(File.separator)).getOrElse("")
+      s"[$path, $path/]"
+    case _ =>
+      Seq(database, table).filter(_ != null).mkString("/")
+  }
+
+  private[ranger] def toResourceInfos: Seq[RangerResourceInfo] = {
+    val attributes = owner.map(o => 
java.util.Collections.singletonMap("OWNER", o: AnyRef)).orNull
+    objectType match {
+      case DATABASE =>
+        Seq(new RangerResourceInfo(
+          s"database:${requireRrnComponent(database, "database")}",
+          null,
+          null,
+          attributes))
+      case FUNCTION =>
+        // An unqualified function reference (e.g. a built-in or temporary 
function) has no
+        // database. The legacy plugin left the database blank, and blank 
values in the legacy
+        // resource matched the wildcard values in policies, so keep the 
wildcard marker for
+        // the blank database. Blank names in other resource levels indicate a 
broken command
+        // extraction, which matched no policy in the legacy resource, so deny 
them.
+        val db = if (StringUtils.isBlank(database)) "*" else 
escapeRrnMetaChars(database)
+        Seq(new RangerResourceInfo(
+          s"udf:$db/${requireRrnComponent(udf, "udf")}",
+          null,
+          null,
+          attributes))
+      case COLUMN =>
+        val columns = getColumns
+        // all the column requests need the database and the table
+        val parent =
+          s"column:${requireRrnComponent(database, "database")}" +

Review Comment:
   `column:db/t` does not parse against the column RRN template 
`{database}/{table}/{column}`. `RangerResourceNameParser.parseToArray` throws 
INVALID_RESOURCE_VALUE when a level is missing, so the no-column and 
multi-column branches always fail. `RuleApplyDataMaskingStage0` and SHOW 
COLUMNS reach them with a column named `a,b` (split by `getColumns`), and every 
query on that table then fails, including for admins.
   
   The mask lookup is for exactly one column, so it should not go through the 
comma split: build `column:db/t/<name>` as one value, as the plugin on master 
did. Switching only the parent to `table:` would hide the problem, because the 
top-level result then carries no data mask and the column would come back 
unmasked. For real multi-column requests, use a `table:` parent with `column:` 
sub-resources, as Ranger's `TestRemoteAuthorizer` does. Please add a test with 
a column name containing a comma.



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala
+      .filter { case (key, _) =>
+        CONFIG_PREFIXES.exists(key.startsWith) && !isAdminOnlyKey(key)
+      }
+      .foreach { case (key, value) => props.put(key, value) }
+    // The Ranger authorizer factory defaults to the embedded authorizer, but 
the
+    // plugin default is the Ranger PDP remote authorizer. Set it explicitly 
when
+    // the configuration does not select an implementation.
+    if (!props.containsKey(KEY_IMPL_CLASS)) {
+      props.put(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    }
+    validateAdminOnlyKeys(props)
+    initialize(props)
+  }
+
+  private[ranger] def isAdminOnlyKey(key: String): Boolean =
+    ADMIN_ONLY_KEYS.contains(key) || 
ADMIN_ONLY_KEY_PREFIXES.exists(key.startsWith)
+
+  /**
+   * Fails fast when the Ranger configuration resources lack a configuration 
the
+   * authorizer needs: the authorizer implementation defaults to the Ranger 
PDP mode,
+   * which requires the Ranger PDP server address. The configuration cannot 
fall back
+   * to JVM system properties, which tenant users may control.
+   */
+  private def validateAdminOnlyKeys(props: Properties): Unit = {
+    val implClass = props.getProperty(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    if (implClass == REMOTE_AUTHORIZER_CLASS && props.getProperty(KEY_PDP_URL) 
== null) {
+      throw new IllegalArgumentException(
+        s"$KEY_PDP_URL must be configured in ${CONFIG_RESOURCES.mkString(", 
")} and " +
+          "cannot be set by JVM system properties")
+    }
+  }
+
+  private def ensureConfig(): Unit = {
+    if (config == null) {
+      config = new Configuration
+      CONFIG_RESOURCES.foreach(addResourceIfReadable)
+    }
+  }
+
+  private def addResourceIfReadable(resource: String): Unit = {
+    val loader = Thread.currentThread().getContextClassLoader
+    val url = if (loader != null) loader.getResource(resource) else null
+    if (url != null) {
+      config.addResource(url)
+    } else {
+      config.addResource(resource)
+    }
   }
 
+  private[ranger] def initialize(props: Properties): Unit = synchronized {
+    if (authorizer == null) {
+      props.put("ranger.authz.app.type", APP_TYPE)
+      authorizer = RangerAuthorizerFactory.createAuthorizer(props)
+      authorizer.init()
+      registerCleanupShutdownHook(authorizer)

Review Comment:
   `authorizer` is assigned before `init()` runs. If `init()` throws (missing 
JWT file, Kerberos login, TLS setup), the half-initialized authorizer is kept 
and `checkInitialized()` never retries. Every later call then fails with 
`AUTHORIZER_CREATION_FAILED`, which hides the original cause. 
`checkInitialized()` also reads the field outside the lock, so it should be 
`@volatile`.
   
   ```suggestion
         val newAuthorizer = RangerAuthorizerFactory.createAuthorizer(props)
         newAuthorizer.init()
         registerCleanupShutdownHook(newAuthorizer)
         authorizer = newAuthorizer
   ```



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/AccessRequest.scala:
##########
@@ -17,81 +17,34 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
-import java.util.{HashMap => JHashMap, Set => JSet}
-import java.util.Date
-
-import scala.collection.JavaConverters._
-
 import org.apache.hadoop.security.UserGroupInformation
-import org.apache.ranger.plugin.policyengine.{RangerAccessRequestImpl, 
RangerPolicyEngine}
 
 import org.apache.kyuubi.plugin.spark.authz.OperationType.OperationType
-import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
-import org.apache.kyuubi.util.reflect.ReflectUtils._
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType.AccessType
 
-case class AccessRequest private (accessType: AccessType) extends 
RangerAccessRequestImpl
+/**
+ * A request to authorize a user for accessing a resource with an access type.
+ *
+ * @param resource   the resource to authorize
+ * @param user       the name of the user to authorize
+ * @param userGroups the groups of the user
+ * @param opType     the Spark SQL operation type requesting the access
+ * @param accessType the access type to authorize
+ */
+case class AccessRequest private[ranger] (
+    resource: AccessResource,
+    user: String,
+    userGroups: Set[String],
+    opType: OperationType,
+    accessType: AccessType)
 
 object AccessRequest {
+
   def apply(
       resource: AccessResource,
       user: UserGroupInformation,
       opType: OperationType,
       accessType: AccessType): AccessRequest = {
-    val userName = user.getShortUserName
-    val userGroups = getUserGroups(user)
-    val req = new AccessRequest(accessType)
-    req.setResource(resource)
-    req.setUser(userName)
-    req.setUserGroups(userGroups)
-    req.setAction(opType.toString)
-    try {
-      val roles = invokeAs[JSet[String]](
-        SparkRangerAdminPlugin,
-        "getRolesFromUserAndGroups",
-        (classOf[String], userName),
-        (classOf[JSet[String]], userGroups))
-      invokeAs[Unit](req, "setUserRoles", (classOf[JSet[String]], roles))
-    } catch {
-      case _: Exception =>
-    }
-    req.setAccessTime(new Date())
-    accessType match {
-      case USE => req.setAccessType(RangerPolicyEngine.ANY_ACCESS)
-      case _ => req.setAccessType(accessType.toString.toLowerCase)
-    }
-    try {
-      val clusterName = invokeAs[String](SparkRangerAdminPlugin, 
"getClusterName")
-      invokeAs[Unit](req, "setClusterName", (classOf[String], clusterName))
-    } catch {
-      case _: Exception =>
-    }
-    req
-  }
-
-  private def getUserGroupsFromUgi(user: UserGroupInformation): JSet[String] = 
{
-    user.getGroupNames.toSet.asJava
-  }
-
-  private def getUserGroupsFromUserStore(user: UserGroupInformation): 
Option[JSet[String]] = {
-    try {
-      val storeEnricher = invokeAs[AnyRef](SparkRangerAdminPlugin, 
"getUserStoreEnricher")
-      val userStore = invokeAs[AnyRef](storeEnricher, "getRangerUserStore")
-      val userGroupMapping =
-        invokeAs[JHashMap[String, JSet[String]]](userStore, 
"getUserGroupMapping")
-      Some(userGroupMapping.get(user.getShortUserName))
-    } catch {
-      case _: NoSuchMethodException =>
-        None
-    }
+    AccessRequest(resource, user.getShortUserName, user.getGroupNames.toSet, 
opType, accessType)

Review Comment:
   Groups now always come from UGI. The plugin on master resolved groups from 
the Ranger UserStore when 
`ranger.plugin.spark.use.usergroups.from.userstore.enabled` was set. That key 
is now silently ignored, so group-scoped masks, row filters and deny policies 
stop matching wherever the driver has no group mapping (e.g. on Kubernetes). 
Please fail fast when the key is set. Please also note in the migration guide 
that PDP mode is now the default, and that in PDP mode 
`ranger.authz.default.use.rangerGroups=true` replaces this key.



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala

Review Comment:
   Merging JVM system properties turns the admin-only list into a denylist, and 
it has gaps. In embedded mode, `-Dranger.plugin.spark.super.users=alice` (or 
`.super.groups`) passes this filter. `RangerAuthzConfig.getServiceProperties` 
keeps `ranger.plugin.spark.*`, and `RangerBasePlugin` makes alice a super user 
who bypasses all policies, row filters and masks. The plugin on master did not 
read system properties. Please drop the merge (L141-145); 
`RangerRemoteAuthorizerSuite` already reads its system properties itself. 
`ADMIN_ONLY_KEYS`, `ADMIN_ONLY_KEY_PREFIXES` and `isAdminOnlyKey` can then go 
too.



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala:
##########
@@ -17,114 +17,381 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import java.util.Properties
+
 import scala.collection.JavaConverters._
 import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
 
+import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.util.ShutdownHookManager
-import org.apache.ranger.plugin.policyengine.RangerAccessRequest
-import org.apache.ranger.plugin.service.RangerBasePlugin
+import org.apache.ranger.authz.api.{RangerAuthorizer, RangerAuthorizerFactory}
+import org.apache.ranger.authz.model._
+import 
org.apache.ranger.authz.model.RangerAccessContext.CONTEXT_INFO_CLUSTER_NAME
+import org.apache.ranger.authz.model.RangerAuthzResult.AccessDecision
 import org.slf4j.LoggerFactory
 
 import org.apache.kyuubi.plugin.spark.authz.AccessControlException
+import org.apache.kyuubi.plugin.spark.authz.ObjectType
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
-  with RangerConfigProvider {
+/**
+ * The entry point of Ranger authorization for Spark SQL, which delegates
+ * authorization requests to a Ranger authorizer:
+ * <ul>
+ *   <li>org.apache.ranger.authz.remote.RangerRemoteAuthorizer (default):
+ *       sends requests to a Ranger PDP server via REST APIs, with a thin 
client
+ *       that does not download policies to the client side.</li>
+ *   <li>org.apache.ranger.authz.embedded.RangerEmbeddedAuthorizer:
+ *       evaluates requests locally against the policies pulled from
+ *       the Ranger admin server, as the previous Ranger plugin did.</li>
+ * </ul>
+ *
+ * The authorizer implementation is selected by `ranger.authorizer.impl.class`.
+ */
+object SparkRangerAdminPlugin {
   final private val LOG = LoggerFactory.getLogger(getClass)
 
+  /**
+   * The service type of the Spark SQL service definition registered in
+   * Ranger admin.
+   */
+  final val SERVICE_TYPE: String = "spark"
+
+  final private val APP_TYPE: String = "sparkSql"
+
+  final private val KEY_IMPL_CLASS = "ranger.authorizer.impl.class"
+  final private val KEY_PDP_URL = "ranger.authz.remote.pdp.url"
+  final private val KEY_SERVICE_NAME = 
s"ranger.plugin.$SERVICE_TYPE.service.name"
+  final private val KEY_CLUSTER_NAME = 
s"ranger.plugin.$SERVICE_TYPE.access.cluster.name"
+  final private val KEY_AUTHORIZE_IN_SINGLE_CALL =
+    s"ranger.plugin.$SERVICE_TYPE.authorize.in.single.call"
+  final private val KEY_POLICY_SOURCE_IMPL =
+    s"ranger.plugin.$SERVICE_TYPE.policy.source.impl"
+  final private val KEY_POLICY_REST_URL = 
s"ranger.plugin.$SERVICE_TYPE.policy.rest.url"
+  final private val KEY_POLICY_CACHE_DIR = 
s"ranger.plugin.$SERVICE_TYPE.policy.cache.dir"
+  final private val KEY_HIVE_POLICY_CACHE_DIR = 
"ranger.plugin.hive.policy.cache.dir"
+  final private val POLICY_ENGINE_DISABLE_PREFIX =
+    s"ranger.plugin.$SERVICE_TYPE.policyengine.option.disable."
+
+  final private val REMOTE_AUTHORIZER_CLASS: String =
+    classOf[org.apache.ranger.authz.remote.RangerRemoteAuthorizer].getName
+
+  /**
+   * The security-critical configurations which are read from the Ranger 
configuration
+   * resources only: JVM system properties can neither set nor override them, 
so a tenant
+   * who can control the JVM options of the engine process cannot point the 
authorization
+   * to a server they control, load policies from another source, or bypass 
the policies.
+   */
+  final private val ADMIN_ONLY_KEYS: Seq[String] = Seq(
+    KEY_IMPL_CLASS,
+    KEY_PDP_URL,
+    KEY_SERVICE_NAME,
+    KEY_POLICY_SOURCE_IMPL,
+    KEY_POLICY_REST_URL,
+    KEY_POLICY_CACHE_DIR,
+    KEY_HIVE_POLICY_CACHE_DIR)
+
+  final private val ADMIN_ONLY_KEY_PREFIXES: Seq[String] = Seq(
+    "ranger.authz.remote.authn.",
+    "ranger.authz.remote.header.",
+    "ranger.authz.remote.ssl.",
+    // aliases that Ranger's embedded authorizer maps to 
ranger.plugin.<serviceType>.*
+    "ranger.authz.default.",
+    "ranger.authz.service.",
+    "ranger.authz.servicetype.",
+    POLICY_ENGINE_DISABLE_PREFIX)
+
+  final private val CONFIG_PREFIXES = Seq("ranger.", "xasecure.")
+
+  final private val CONFIG_RESOURCES = Seq(
+    s"ranger-$SERVICE_TYPE-security.xml",
+    s"ranger-$SERVICE_TYPE-audit.xml")
+
+  private var authorizer: RangerAuthorizer = null
+
+  /**
+   * The Ranger configurations loaded from the Hadoop configuration resources,
+   * e.g. ranger-spark-security.xml.
+   */
+  private[ranger] var config: Configuration = null
+
   /**
    * For a Spark SQL query, it may contain 0 or more privilege objects to 
verify, e.g. a typical
    * JOIN operator may have two tables and their columns to verify.
    *
    * This configuration controls whether to verify the privilege objects in 
single call or
    * to verify them one by one.
    */
-  def authorizeInSingleCall: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.${getServiceType}.authorize.in.single.call",
-    false)
+  def authorizeInSingleCall: Boolean = 
config.getBoolean(KEY_AUTHORIZE_IN_SINGLE_CALL, false)
 
-  /**
-   * This configuration controls whether to override user's usergroups
-   * by the mapping fetched from Ranger's UserStore.
-   *
-   * It relies on Ranger's UserStore is a feature supported since Ranger 2.1.
-   *
-   * If true, user bound usergroups will be looked up in in Ranger's UserStore
-   * and the usergroups of AccessRequest is overriden.
-   *
-   * Please make sure configs in Ranger set properly:
-   * 1. set `ranger.plugin.spark.enable.implicit.userstore.enricher` to true
-   * 2. set cache path for UserStore in `ranger.plugin.hive.policy.cache.dir`
-   * 3. at least one condition of policies containing scripts, e.g. 
{{USER.attr}} in row-filter
-   */
-  def useUserGroupsFromUserStoreEnabled: Boolean = getRangerConf.getBoolean(
-    s"ranger.plugin.$getServiceType.use.usergroups.from.userstore.enabled",
-    false)
+  def getServiceType: String = SERVICE_TYPE
+
+  private def serviceName: String = config.get(KEY_SERVICE_NAME)
 
   /**
-   * plugin initialization
+   * authorizer initialization
    * with cleanup shutdown hook registered
    */
   def initialize(): Unit = {
-    this.init()
-    registerCleanupShutdownHook(this)
+    ensureConfig()
+    val props = new Properties
+    config.iterator.asScala
+      .filter(entry => CONFIG_PREFIXES.exists(entry.getKey.startsWith))
+      .foreach(entry => props.put(entry.getKey, entry.getValue))
+    System.getProperties.asScala
+      .filter { case (key, _) =>
+        CONFIG_PREFIXES.exists(key.startsWith) && !isAdminOnlyKey(key)
+      }
+      .foreach { case (key, value) => props.put(key, value) }
+    // The Ranger authorizer factory defaults to the embedded authorizer, but 
the
+    // plugin default is the Ranger PDP remote authorizer. Set it explicitly 
when
+    // the configuration does not select an implementation.
+    if (!props.containsKey(KEY_IMPL_CLASS)) {
+      props.put(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    }
+    validateAdminOnlyKeys(props)
+    initialize(props)
+  }
+
+  private[ranger] def isAdminOnlyKey(key: String): Boolean =
+    ADMIN_ONLY_KEYS.contains(key) || 
ADMIN_ONLY_KEY_PREFIXES.exists(key.startsWith)
+
+  /**
+   * Fails fast when the Ranger configuration resources lack a configuration 
the
+   * authorizer needs: the authorizer implementation defaults to the Ranger 
PDP mode,
+   * which requires the Ranger PDP server address. The configuration cannot 
fall back
+   * to JVM system properties, which tenant users may control.
+   */
+  private def validateAdminOnlyKeys(props: Properties): Unit = {
+    val implClass = props.getProperty(KEY_IMPL_CLASS, REMOTE_AUTHORIZER_CLASS)
+    if (implClass == REMOTE_AUTHORIZER_CLASS && props.getProperty(KEY_PDP_URL) 
== null) {
+      throw new IllegalArgumentException(
+        s"$KEY_PDP_URL must be configured in ${CONFIG_RESOURCES.mkString(", 
")} and " +
+          "cannot be set by JVM system properties")
+    }
+  }
+
+  private def ensureConfig(): Unit = {
+    if (config == null) {
+      config = new Configuration
+      CONFIG_RESOURCES.foreach(addResourceIfReadable)
+    }
+  }
+
+  private def addResourceIfReadable(resource: String): Unit = {
+    val loader = Thread.currentThread().getContextClassLoader
+    val url = if (loader != null) loader.getResource(resource) else null
+    if (url != null) {
+      config.addResource(url)
+    } else {
+      config.addResource(resource)
+    }
   }
 
+  private[ranger] def initialize(props: Properties): Unit = synchronized {
+    if (authorizer == null) {
+      props.put("ranger.authz.app.type", APP_TYPE)
+      authorizer = RangerAuthorizerFactory.createAuthorizer(props)
+      authorizer.init()
+      registerCleanupShutdownHook(authorizer)
+      LOG.info(
+        s"initialized ranger authorizer, service: $serviceName, " +
+          s"impl: ${authorizer.getClass.getName}")
+    }
+  }
+
+  private[ranger] def authorizerClassName: String =
+    if (authorizer == null) null else authorizer.getClass.getName
+
   /**
-   * register shutdown hook for plugin cleanup
+   * Reset the authorizer to the uninitialized state, so that the next
+   * [[initialize]] call re-creates it. Intended for tests only.
    */
-  private def registerCleanupShutdownHook(plugin: RangerBasePlugin): Unit = {
+  private[ranger] def reset(): Unit = synchronized {
+    if (authorizer != null) {
+      try authorizer.close()
+      catch {
+        case e: Exception => LOG.warn("failed to close ranger authorizer", e)
+      }
+      authorizer = null
+    }
+  }
+
+  private def registerCleanupShutdownHook(authorizer: RangerAuthorizer): Unit 
= {
     ShutdownHookManager.get().addShutdownHook(
       () => {
-        if (plugin != null) {
-          LOG.info(s"clean up ranger plugin, appId: ${plugin.getAppId}")
-          plugin.cleanup()
-          plugin.getAuditProviderFactory.shutdown()
+        if (authorizer != null) {
+          LOG.info(s"clean up ranger authorizer, impl: 
${authorizer.getClass.getName}")
+          try authorizer.close()
+          catch {
+            case e: Exception => LOG.warn("failed to close ranger authorizer", 
e)
+          }
         }
       },
       Integer.MAX_VALUE)
   }
 
+  private def checkInitialized(): RangerAuthorizer = {
+    if (authorizer == null) {
+      initialize()
+    }
+    authorizer
+  }
+
+  private def userInfo(req: AccessRequest): RangerUserInfo =
+    new RangerUserInfo(req.user, null, req.userGroups.asJava, null)
+
+  private def permissionOf(accessType: AccessType): String = accessType match {
+    // the Ranger any-access marker (RangerPolicyEngine.ANY_ACCESS) allows any 
access
+    // type matched by policies, e.g. for SHOW commands
+    case USE => "_any"
+    case _ => accessType.toString.toLowerCase
+  }
+
+  private def context(): RangerAccessContext = {
+    val additionalInfo = new java.util.HashMap[String, AnyRef]
+    val clusterName = config.get(KEY_CLUSTER_NAME)
+    if (clusterName != null) {
+      additionalInfo.put(CONTEXT_INFO_CLUSTER_NAME, clusterName)
+    }
+    val ctx = new RangerAccessContext(SERVICE_TYPE, serviceName)
+    ctx.setAccessTime(System.currentTimeMillis)
+    ctx.setAdditionalInfo(additionalInfo)
+    ctx
+  }
+
+  private def toAuthzRequest(
+      req: AccessRequest,
+      resourceInfo: RangerResourceInfo): RangerAuthzRequest = {
+    val access = new RangerAccessInfo(
+      resourceInfo,
+      req.opType.toString,
+      java.util.Collections.singleton(permissionOf(req.accessType)))
+    new RangerAuthzRequest(userInfo(req), access, context())
+  }
+
+  private def toAuthzRequest(req: AccessRequest): RangerAuthzRequest =
+    toAuthzRequest(req, req.resource.toResourceInfos.head)
+
+  /**
+   * batch verifying RangerAccessRequests
+   * and throws exception with all disallowed privileges
+   * for accessType and resources
+   */
+  def verify(requests: Seq[AccessRequest]): Unit = {
+    if (requests.nonEmpty) {
+      val authorizer = checkInitialized()
+      val user = userInfo(requests.head)
+      val ctx = context()
+      // a uri resource has two variants, the exact path and the path with a 
trailing
+      // slash, which are authorized as alternatives by separate requests; the 
single
+      // call authorizes a fixed set of accesses conjunctively, so it is used 
only when
+      // the requests contain no uri resource
+      val hasUri = requests.exists(_.resource.objectType == ObjectType.URI)
+      val results = if (authorizeInSingleCall && !hasUri) {
+        val accesses = requests.map(toAuthzRequest(_).getAccess).asJava
+        (for {
+          multiResult <-
+            Option(authorizer.authorize(new RangerMultiAuthzRequest(user, 
accesses, ctx)))
+          accessResults <- Option(multiResult.getAccesses)
+        } yield 
accessResults.asScala.map(Option(_)).toSeq).getOrElse(Seq.empty)
+      } else {
+        requests.map { req =>
+          val variantResults = req.resource.toResourceInfos.map { resourceInfo 
=>
+            Option(authorizer.authorize(toAuthzRequest(req, resourceInfo)))
+          }
+          variantResults.find(_.exists(_.getDecision == AccessDecision.ALLOW))
+            .getOrElse(variantResults.head)
+        }
+      }
+
+      // a missing result means the authorizer could not evaluate the request,
+      // which is denied instead of skipped
+      val indices = results.padTo(requests.length, None).zipWithIndex.collect {
+        case (result, idx) if result.forall(_.getDecision != 
AccessDecision.ALLOW) => idx
+      }
+      if (indices.nonEmpty) {
+        val accessTypeToResource =
+          indices.foldLeft(LinkedHashMap.empty[String, 
ArrayBuffer[String]])((m, idx) => {
+            val req = requests(idx)
+            val accessType = permissionOf(req.accessType)
+            val resource = req.resource.getAsString
+            m.getOrElseUpdate(accessType, ArrayBuffer.empty[String])
+              .append(resource)
+            m
+          })
+        val errorMsg = accessTypeToResource
+          .map { case (accessType, resources) =>
+            s"[$accessType] ${resources.mkString("privilege on [", ",", "]")}"
+          }.mkString(", ")
+        throw new AccessControlException(
+          s"Permission denied: user [${requests.head.user}] does not have 
$errorMsg")
+      }
+    }
+  }
+
+  private def requireResult(result: RangerAuthzResult, req: AccessRequest): 
RangerAuthzResult =
+    if (result == null) {
+      // a missing result means the authorizer could not evaluate the request,
+      // which must not be treated as allowed
+      throw new AccessControlException(
+        s"Permission denied: no authorization result for user [${req.user}], " 
+
+          s"resource [${req.resource.getAsString}]")
+    } else {
+      result
+    }
+
   def getFilterExpr(req: AccessRequest): Option[String] = {
-    val result = evalRowFilterPolicies(req, null)
+    val result = 
requireResult(checkInitialized().authorize(toAuthzRequest(req)), req)
     Option(result)
-      .filter(_.isRowFilterEnabled)
+      .filter(_.getDecision == AccessDecision.ALLOW)
+      .flatMap { r =>
+        Option(r.getPermissions.get(permissionOf(req.accessType)))
+      }
+      .map(_.getRowFilter)
+      .filter(rf => rf != null && rf.getFilterExpr != null && 
rf.getFilterExpr.nonEmpty)
       .map(_.getFilterExpr)
-      .filter(fe => fe != null && fe.nonEmpty)
   }
 
   def getMaskingExpr(req: AccessRequest): Option[String] = {
-    val col = req.getResource.asInstanceOf[AccessResource].getColumn
-    val result = evalDataMaskPolicies(req, null)
-    Option(result).filter(_.isMaskEnabled).map { res =>
-      if ("MASK_NULL".equalsIgnoreCase(res.getMaskType)) {
-        "NULL"
-      } else if ("CUSTOM".equalsIgnoreCase(result.getMaskType)) {
-        val maskVal = res.getMaskedValue
-        if (maskVal == null) {
+    val col = req.resource.getColumn
+    val result = 
requireResult(checkInitialized().authorize(toAuthzRequest(req)), req)

Review Comment:
   Non-blocking: `getMaskingExpr` and `getFilterExpr` now go through 
`authorize()`, which runs and audits the access check along with the mask or 
row filter (`RangerAuthzPlugin.evaluate` passes the audit handler to 
`isAccessAllowed`). The plugin on master called `evalDataMaskPolicies(req, 
null)` and `evalRowFilterPolicies(req, null)` without audit. The mask lookup 
runs per output column, so `SELECT *` on a 200-column table can write an audit 
record per column. In PDP mode it also makes about 200 sequential HTTP calls on 
top of `verify`. Batching the mask lookup per table into one request with 
`column:` sub-resources would cut this to one call, since each sub-resource 
result carries its own data mask.



##########
extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/AccessResource.scala:
##########
@@ -18,27 +18,167 @@
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
 import java.io.File
-import java.util
 
-import scala.language.implicitConversions
+import scala.collection.JavaConverters._
 
-import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl
+import org.apache.commons.lang3.StringUtils
+import org.apache.ranger.authz.model.RangerResourceInfo
 
-import org.apache.kyuubi.plugin.spark.authz.{ObjectType, PrivilegeObject}
+import org.apache.kyuubi.plugin.spark.authz.{AccessControlException, 
ObjectType, PrivilegeObject}
 import org.apache.kyuubi.plugin.spark.authz.ObjectType._
 import org.apache.kyuubi.plugin.spark.authz.OperationType.OperationType
 
-class AccessResource private (val objectType: ObjectType, val catalog: 
Option[String])
-  extends RangerAccessResourceImpl {
-  implicit def asString(obj: Object): String = if (obj != null) 
obj.asInstanceOf[String] else null
-  def getDatabase: String = getValue("database")
-  def getUdf: String = getValue("udf")
-  def getTable: String = getValue("table")
-  def getColumn: String = getValue("column")
+/**
+ * A privilege object to authorize, which is converted to a Ranger resource
+ * (e.g. "table:default/src" or "column:default/src/id") in requests to
+ * the Ranger authorizer.
+ *
+ * @param objectType the type of the object
+ * @param database   the database name, or null if not applicable
+ * @param table      the table name, or null if not applicable
+ * @param column     the column names joined by comma, or null if not 
applicable
+ * @param udf        the function name, or null if not applicable
+ * @param uri        the uri path, or null if not applicable
+ * @param owner      the owner of the object, if any
+ * @param catalog    the catalog name, if any
+ */
+case class AccessResource private[ranger] (
+    objectType: ObjectType,
+    database: String,
+    table: String,
+    column: String,
+    udf: String,
+    uri: String,
+    owner: Option[String],
+    catalog: Option[String]) {
+
+  def getDatabase: String = database
+  def getUdf: String = udf
+  def getTable: String = table
+  def getColumn: String = column
+
   def getColumns: Seq[String] = {
-    val columnStr = getColumn
-    if (columnStr == null) Nil else columnStr.split(",").filter(_.nonEmpty)
+    if (column == null) Nil else column.split(",").filter(_.nonEmpty)
   }
+
+  def getOwnerUser: String = owner.orNull
+
+  /**
+   * The path-like representation of this resource used in error messages,
+   * e.g. "default/src" for a table, "default/src/id" for a column.
+   */
+  def getAsString: String = objectType match {
+    case COLUMN =>
+      Seq(database, table, column).filter(_ != null).mkString("/")
+    case FUNCTION =>
+      Seq(database, udf).filter(_ != null).mkString("/")
+    case URI =>
+      // the uri is matched against both the exact path and the path with a
+      // trailing slash, as the legacy plugin did
+      val path = Option(uri).map(_.stripSuffix(File.separator)).getOrElse("")
+      s"[$path, $path/]"
+    case _ =>
+      Seq(database, table).filter(_ != null).mkString("/")
+  }
+
+  private[ranger] def toResourceInfos: Seq[RangerResourceInfo] = {
+    val attributes = owner.map(o => 
java.util.Collections.singletonMap("OWNER", o: AnyRef)).orNull
+    objectType match {
+      case DATABASE =>
+        Seq(new RangerResourceInfo(
+          s"database:${requireRrnComponent(database, "database")}",
+          null,
+          null,
+          attributes))
+      case FUNCTION =>
+        // An unqualified function reference (e.g. a built-in or temporary 
function) has no
+        // database. The legacy plugin left the database blank, and blank 
values in the legacy
+        // resource matched the wildcard values in policies, so keep the 
wildcard marker for
+        // the blank database. Blank names in other resource levels indicate a 
broken command
+        // extraction, which matched no policy in the legacy resource, so deny 
them.
+        val db = if (StringUtils.isBlank(database)) "*" else 
escapeRrnMetaChars(database)
+        Seq(new RangerResourceInfo(
+          s"udf:$db/${requireRrnComponent(udf, "udf")}",
+          null,
+          null,
+          attributes))
+      case COLUMN =>
+        val columns = getColumns
+        // all the column requests need the database and the table
+        val parent =
+          s"column:${requireRrnComponent(database, "database")}" +
+            s"/${requireRrnComponent(table, "table")}"
+        if (columns.length == 1) {
+          Seq(new RangerResourceInfo(
+            s"$parent/${requireRrnComponent(columns.head, "column")}",
+            null,
+            null,
+            attributes))
+        } else if (columns.isEmpty) {
+          Seq(new RangerResourceInfo(parent, null, null, attributes))
+        } else {
+          val subResources = columns
+            .map(col => s"column:${requireRrnComponent(col, "column")}")
+            .toSet.asJava
+          Seq(new RangerResourceInfo(parent, subResources, null, attributes))
+        }
+      case URI =>
+        // Url policies may be written with or without a trailing slash, and 
the legacy
+        // plugin matched a uri against both the exact path and the path with 
a trailing
+        // slash. The RRN request carries a single resource value set, so the 
two variants
+        // are returned and authorized as alternatives by separate requests.
+        val path = requireRrnComponent(
+          Option(uri).map(_.stripSuffix(File.separator)).orNull,

Review Comment:
   Minor: for uri `/`, `stripSuffix` leaves an empty string, so 
`requireRrnComponent` denies it even for a user with a `*` url policy (e.g. 
`LOAD DATA INPATH '/'`). The plugin on master evaluated `["", "/"]`, so `/` 
could match. Please keep `/` as is for the root path, and add a test.



##########
extensions/spark/kyuubi-spark-authz/src/test/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RangerRemoteAuthorizerSuite.scala:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kyuubi.plugin.spark.authz.ranger
+
+import java.util.Properties
+
+import scala.collection.JavaConverters._
+
+import org.apache.hadoop.security.UserGroupInformation
+
+import org.apache.kyuubi.KyuubiFunSuite
+import org.apache.kyuubi.plugin.spark.authz.{AccessControlException, 
OperationType}
+import org.apache.kyuubi.plugin.spark.authz.ObjectType._
+import org.apache.kyuubi.plugin.spark.authz.RangerTestUsers._
+import org.apache.kyuubi.plugin.spark.authz.ranger.AccessType._
+
+/**
+ * The tests exercise the Ranger PDP remote authorizer (the default), which 
sends
+ * authorization requests to a Ranger PDP server via REST APIs.
+ *
+ * By default, the requests go to [[MockPdpServer]] backed by the same 
policies used
+ * by the other suites. To validate against a real Ranger PDP server, start one
+ * configured with the same service (hive_jenkins) and policies, then run this 
suite
+ * with the Ranger PDP server url and the Ranger PDP client settings, e.g. the
+ * authentication settings, specified as system properties, e.g.
+ * {{{
+ * mvn test -pl extensions/spark/kyuubi-spark-authz \
+ *   -DforkMode=never \
+ *   
-DwildcardSuites=org.apache.kyuubi.plugin.spark.authz.ranger.RangerRemoteAuthorizerSuite
 \
+ *   -Dranger.authz.remote.pdp.url=https://ranger-pdp.org:8585 \
+ *   -Dranger.authz.remote.authn.type=header \
+ *   -Dranger.authz.remote.authn.header.X-Forwarded-User=ranger
+ * }}}
+ *
+ * The plugin reads the security-critical Ranger configurations from the 
configuration
+ * resources only, so the suite passes them to the plugin explicitly; the 
system
+ * properties above are consumed by this suite.
+ *
+ * Note that `-DforkMode=never` is required to run the tests in the maven JVM 
so
+ * that the system properties reach the suite.
+ */
+class RangerRemoteAuthorizerSuite extends KyuubiFunSuite {
+
+  private val RemoteAuthorizer = 
"org.apache.ranger.authz.remote.RangerRemoteAuthorizer"
+
+  // when a real Ranger PDP server is given via the system property,
+  // the mock server is not started
+  private lazy val mockPdp: Option[MockPdpServer] =
+    if (System.getProperty("ranger.authz.remote.pdp.url") == null) {
+      Some(new MockPdpServer)
+    } else {
+      None
+    }
+
+  private def pdpUrl: String =
+    System.getProperty("ranger.authz.remote.pdp.url", 
mockPdp.map(_.url).orNull)
+
+  private def ugiOf(user: String): UserGroupInformation =
+    UserGroupInformation.createRemoteUser(user)
+
+  private def tableReq(user: String, db: String, table: String, accessType: 
AccessType) =
+    AccessRequest(
+      AccessResource(TABLE, db, table, null),
+      ugiOf(user),
+      OperationType.QUERY,
+      accessType)
+
+  private def initializeRemoteAuthorizer(): Unit = {
+    // ensures the Ranger configuration resources are loaded
+    SparkRangerAdminPlugin.initialize()
+    val properties = new Properties
+    // the Ranger PDP client settings, e.g. the authentication settings,
+    // can be specified as system properties of the test JVM
+    System.getProperties.asScala
+      .filter { case (key, _) => key.startsWith("ranger.authz.remote.") }
+      .foreach { case (key, value) => properties.put(key, value) }
+    properties.setProperty("ranger.authorizer.impl.class", RemoteAuthorizer)
+    properties.setProperty("ranger.authz.remote.pdp.url", pdpUrl)
+    SparkRangerAdminPlugin.reset()
+    SparkRangerAdminPlugin.initialize(properties)
+  }
+
+  override def afterAll(): Unit = {
+    SparkRangerAdminPlugin.reset()
+    SparkRangerAdminPlugin.initialize()
+    mockPdp.foreach(_.close())
+    super.afterAll()
+  }
+
+  // the authorizer may be re-initialized by other suites running in the same 
JVM
+  override def beforeEach(): Unit = {
+    initializeRemoteAuthorizer()
+    super.beforeEach()
+  }
+
+  test("verify allowed access") {
+    SparkRangerAdminPlugin.verify(Seq(tableReq(bob, "default", "src", SELECT)))
+    SparkRangerAdminPlugin.verify(
+      Seq(
+        AccessRequest(
+          AccessResource(COLUMN, "default", "src", "key"),
+          ugiOf(kent),
+          OperationType.QUERY,
+          SELECT)))
+  }
+
+  test("verify denied access") {
+    val e = intercept[AccessControlException] {
+      SparkRangerAdminPlugin.verify(Seq(tableReq(someone, "default", "src", 
SELECT)))
+    }
+    assert(e.getMessage.contains(s"does not have [select] privilege on 
[default/src]"))
+  }
+
+  test("verify multiple denied accesses in single call") {

Review Comment:
   This suite never enables `ranger.plugin.spark.authorize.in.single.call`, and 
neither does the test `ranger-spark-security.xml`. So this test goes through 
the per-request path, and the mock's `/authz/v1/authorizeMulti` handler is 
never hit. Likewise, `access allowed for uri` (L170) uses `isAccessAllowed`, 
which sends only the exact-path variant (`toResourceInfos.head`), so the uri 
variant handling in `verify` is not covered either. The extension suites run 
against the embedded authorizer only, which leaves this suite as the only 
coverage of the default PDP path. Please enable single-call mode for this test 
(as `SparkRangerAdminPluginSuite` does), and cover uris through `verify`, 
including a deny on one variant.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to