You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kyuubi.apache.org by ya...@apache.org on 2022/09/02 09:18:06 UTC

[incubator-kyuubi] branch master updated: [KYUUBI #3371] [FEATURE] [AUTHZ] Support checking access privileges in single call and throws all disallowed in exception

This is an automated email from the ASF dual-hosted git repository.

yao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-kyuubi.git


The following commit(s) were added to refs/heads/master by this push:
     new 23a8ccd53 [KYUUBI #3371] [FEATURE] [AUTHZ] Support checking access privileges in single call and throws all disallowed in exception
23a8ccd53 is described below

commit 23a8ccd538c72ba38770941928f5a7e161dd2af7
Author: Bowen Liang <li...@gf.com.cn>
AuthorDate: Fri Sep 2 17:17:56 2022 +0800

    [KYUUBI #3371] [FEATURE] [AUTHZ] Support checking access privileges in single call and throws all disallowed in exception
    
    ### _Why are the changes needed?_
    
    to close #3371
    
    Adding an ranger plugin config for enabling full access privileges,  Authz checks all access privileges and throw exception with message of unsatisfied  privileges on different resources in natural order in execution plan.
    
    ### _How was this patch tested?_
    - [x] Add some test cases that check the changes thoroughly including negative and positive cases if possible
    
    - [ ] Add screenshots for manual tests if appropriate
    
    - [x] [Run test](https://kyuubi.apache.org/docs/latest/develop_tools/testing.html#running-tests) locally before make a pull request
    
    Closes #3380 from bowenliang123/3371-authz-full-check.
    
    Closes #3371
    
    9326196d [Bowen Liang] add RangerConfigProvider for getting plugin config of different Ranger versions. add invokeStatic in AuthZUtils.
    65d765dd [Bowen Liang] use ArrayBuffer for value of accessTypeToResource map. import scala LinkedHashMap.
    959cd7dc [liangbowen] nit: update ut
    dbfd3479 [liangbowen] 1.use LinkedHashMap and LinkedHashSet for keeping in natual order for consistent error msg output, 2. update ut
    3e0a5feb [liangbowen] revert to not enforcing output error message in alphabet order
    1df4130d [Bowen Liang] add ut with multiple input tables and one output table
    5241fd6a [Bowen Liang] refactor verify method in more scala style
    d7bc6841 [Bowen Liang] nit
    32b2dd6d [Bowen Liang] nit: docs
    d9787be4 [Bowen Liang] nit: docs
    87b095cf [Bowen Liang] simplify verify method
    a0d27e0c [Bowen Liang] simplify verify method and update docs
    c9b4e065 [Bowen Liang] rename config to ranger.plugin.plugin.authorize.in.single.call, simplify access checking, and related docs
    f6ccc1ac [liangbowen] move verify to SparkRangerAdminPlugin and change config name to ranger.plugin.spark.enable.full.access.violation.msg
    c531cadb [Bowen Liang] add config doc in Authz
    041c49b1 [Bowen Liang] move config to ranger plugin conf
    f4fbeb23 [liangbowen] support for full access checking
    
    Lead-authored-by: Bowen Liang <li...@gf.com.cn>
    Co-authored-by: liangbowen <li...@gf.com.cn>
    Signed-off-by: Kent Yao <ya...@apache.org>
---
 docs/security/authorization/spark/install.md       | 10 ++++
 .../spark/authz/ranger/RuleAuthorization.scala     | 42 +++++-----------
 .../authz/ranger/SparkRangerAdminPlugin.scala      | 57 +++++++++++++++++++++-
 .../plugin/spark/authz/util/AuthZUtils.scala       | 12 ++++-
 .../spark/authz/util/RangerConfigProvider.scala    | 49 +++++++++++++++++++
 .../authz/ranger/RangerSparkExtensionSuite.scala   | 45 +++++++++++++++++
 6 files changed, 183 insertions(+), 32 deletions(-)

diff --git a/docs/security/authorization/spark/install.md b/docs/security/authorization/spark/install.md
index ec2892230..1d77d15b5 100644
--- a/docs/security/authorization/spark/install.md
+++ b/docs/security/authorization/spark/install.md
@@ -92,6 +92,16 @@ Macros are now supported for using user/group/tag in row filter expressions, int
     </property>    
 ```
 
+##### Showing all disallowed privileges
+By default, Authz plugin checks required privileges one by one and throw the first unsatisfied privilege in exception. By setting `ranger.plugin.spark.authorize.in.single.call` to `true`, Authz plugin executes access checks in single call and throws all disallowed privileges in exception message.
+```xml
+    <property>
+        <name>ranger.plugin.spark.authorize.in.single.call</name>
+        <value>true</value>
+        <description>Enable access checks in single call with all disallowed privileges thrown in exception. Default value is false.</description>
+    </property>
+```
+
 #### ranger-spark-audit.xml
 
 Create `ranger-spark-audit.xml` in `$SPARK_HOME/conf` and add the following configurations
diff --git a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RuleAuthorization.scala b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RuleAuthorization.scala
index d8b8f0625..a5f7e53f9 100644
--- a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RuleAuthorization.scala
+++ b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RuleAuthorization.scala
@@ -17,23 +17,19 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
-import java.util
-
-import scala.collection.JavaConverters._
 import scala.collection.mutable.ArrayBuffer
 
-import org.apache.commons.collections.CollectionUtils
 import org.apache.ranger.plugin.policyengine.RangerAccessRequest
 import org.apache.spark.sql.SparkSession
 import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
 import org.apache.spark.sql.catalyst.rules.Rule
 import org.apache.spark.sql.catalyst.trees.TreeNodeTag
 
-import org.apache.kyuubi.plugin.spark.authz.{AccessControlException, ObjectType, _}
+import org.apache.kyuubi.plugin.spark.authz._
 import org.apache.kyuubi.plugin.spark.authz.ObjectType._
 import org.apache.kyuubi.plugin.spark.authz.ranger.RuleAuthorization.KYUUBI_AUTHZ_TAG
-import org.apache.kyuubi.plugin.spark.authz.util.AuthZUtils._
-
+import org.apache.kyuubi.plugin.spark.authz.ranger.SparkRangerAdminPlugin._
+import org.apache.kyuubi.plugin.spark.authz.util.AuthZUtils._;
 class RuleAuthorization(spark: SparkSession) extends Rule[LogicalPlan] {
   override def apply(plan: LogicalPlan): LogicalPlan = plan match {
     case p if !plan.getTagValue(KYUUBI_AUTHZ_TAG).contains(true) =>
@@ -73,37 +69,23 @@ object RuleAuthorization {
     addAccessRequest(inputs, isInput = true)
     addAccessRequest(outputs, isInput = false)
 
-    requests.foreach { request =>
+    val requestArrays = requests.map { request =>
       val resource = request.getResource.asInstanceOf[AccessResource]
       resource.objectType match {
         case ObjectType.COLUMN if resource.getColumns.nonEmpty =>
-          val reqs = resource.getColumns.map { col =>
+          resource.getColumns.map { col =>
             val cr = AccessResource(COLUMN, resource.getDatabase, resource.getTable, col)
             AccessRequest(cr, ugi, opType, request.accessType).asInstanceOf[RangerAccessRequest]
-          }.asJava
-          verify(reqs, auditHandler)
-        case _ => verify(util.Collections.singletonList(request), auditHandler)
+          }
+        case _ => Seq(request)
       }
     }
-  }
 
-  @throws[AccessControlException]
-  private def verify(
-      requests: util.List[RangerAccessRequest],
-      auditHandler: SparkRangerAuditHandler): Unit = {
-    if (CollectionUtils.isEmpty(requests)) {
-      return
-    }
-
-    val results = SparkRangerAdminPlugin.isAccessAllowed(requests, auditHandler)
-    if (CollectionUtils.isNotEmpty(results)) {
-      requests.asScala.zip(results.asScala).foreach {
-        case (req, result) =>
-          if (result != null && !result.getIsAllowed) {
-            throw new AccessControlException(
-              s"Permission denied: user [${req.getUser}] does not have [${req.getAccessType}]" +
-                s" privilege on [${req.getResource.getAsString}]")
-          }
+    if (authorizeInSingleCall) {
+      verify(requestArrays.flatten, auditHandler)
+    } else {
+      requestArrays.flatten.foreach { req =>
+        verify(Seq(req), auditHandler)
       }
     }
   }
diff --git a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala
index a72c2eb75..2a7467a40 100644
--- a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala
+++ b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/ranger/SparkRangerAdminPlugin.scala
@@ -17,11 +17,30 @@
 
 package org.apache.kyuubi.plugin.spark.authz.ranger
 
+import scala.collection.JavaConverters._
+import scala.collection.mutable.ArrayBuffer
+import scala.collection.mutable.LinkedHashMap
+
+import org.apache.ranger.plugin.policyengine.RangerAccessRequest
 import org.apache.ranger.plugin.service.RangerBasePlugin
 
+import org.apache.kyuubi.plugin.spark.authz.AccessControlException
 import org.apache.kyuubi.plugin.spark.authz.util.AuthZUtils._
+import org.apache.kyuubi.plugin.spark.authz.util.RangerConfigProvider
+
+object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql")
+  with RangerConfigProvider {
 
-object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql") {
+  /**
+   * 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 getFilterExpr(req: AccessRequest): Option[String] = {
     val result = evalRowFilterPolicies(req, null)
@@ -76,4 +95,40 @@ object SparkRangerAdminPlugin extends RangerBasePlugin("spark", "sparkSql") {
     val digits = s"regexp_replace($lower, '[0-9]', 'n'$pos)"
     digits
   }
+
+  /**
+   * batch verifying RangerAccessRequests
+   * and throws exception with all disallowed privileges
+   * for accessType and resources
+   */
+  def verify(
+      requests: Seq[RangerAccessRequest],
+      auditHandler: SparkRangerAuditHandler): Unit = {
+    if (requests.nonEmpty) {
+      val results = SparkRangerAdminPlugin.isAccessAllowed(requests.asJava, auditHandler)
+      if (results != null) {
+        val indices = results.asScala.zipWithIndex.filter { case (result, idx) =>
+          result != null && !result.getIsAllowed
+        }.map(_._2)
+        if (indices.nonEmpty) {
+          val user = requests.head.getUser
+          val accessTypeToResource =
+            indices.foldLeft(LinkedHashMap.empty[String, ArrayBuffer[String]])((m, idx) => {
+              val req = requests(idx)
+              val accessType = req.getAccessType
+              val resource = req.getResource.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 [$user] does not have $errorMsg")
+        }
+      }
+    }
+  }
 }
diff --git a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/AuthZUtils.scala b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/AuthZUtils.scala
index 409f34207..b7977713a 100644
--- a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/AuthZUtils.scala
+++ b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/AuthZUtils.scala
@@ -48,7 +48,17 @@ private[authz] object AuthZUtils {
       methodName: String,
       args: (Class[_], AnyRef)*): AnyRef = {
     val (types, values) = args.unzip
-    val method = obj.getClass.getDeclaredMethod(methodName, types: _*)
+    val method = obj.getClass.getMethod(methodName, types: _*)
+    method.setAccessible(true)
+    method.invoke(obj, values: _*)
+  }
+
+  def invokeStatic(
+      obj: Class[_],
+      methodName: String,
+      args: (Class[_], AnyRef)*): AnyRef = {
+    val (types, values) = args.unzip
+    val method = obj.getMethod(methodName, types: _*)
     method.setAccessible(true)
     method.invoke(obj, values: _*)
   }
diff --git a/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/RangerConfigProvider.scala b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/RangerConfigProvider.scala
new file mode 100644
index 000000000..b53ecae0f
--- /dev/null
+++ b/extensions/spark/kyuubi-spark-authz/src/main/scala/org/apache/kyuubi/plugin/spark/authz/util/RangerConfigProvider.scala
@@ -0,0 +1,49 @@
+/*
+ * 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.util
+
+import org.apache.hadoop.conf.Configuration
+
+import org.apache.kyuubi.plugin.spark.authz.util.AuthZUtils._
+
+trait RangerConfigProvider {
+
+  /**
+   * Get plugin config of different Ranger versions
+   *
+   * @return instance of
+   *         org.apache.ranger.authorization.hadoop.config.RangerPluginConfig
+   *         for Ranger 2.1 and above,
+   *         or instance of
+   *         org.apache.ranger.authorization.hadoop.config.RangerConfiguration
+   *         for Ranger 2.0 and below
+   */
+  def getRangerConf: Configuration = {
+    try {
+      // for Ranger 2.1+
+      invoke(this, "getConfig").asInstanceOf[Configuration]
+    } catch {
+      case _: NoSuchMethodException =>
+        // for Ranger 2.0 and below
+        invokeStatic(
+          Class.forName("org.apache.ranger.authorization.hadoop.config.RangerConfiguration"),
+          "getInstance")
+          .asInstanceOf[Configuration]
+    }
+  }
+}
diff --git a/extensions/spark/kyuubi-spark-authz/src/test/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RangerSparkExtensionSuite.scala b/extensions/spark/kyuubi-spark-authz/src/test/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RangerSparkExtensionSuite.scala
index 8006e870b..2ad93bf8b 100644
--- a/extensions/spark/kyuubi-spark-authz/src/test/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RangerSparkExtensionSuite.scala
+++ b/extensions/spark/kyuubi-spark-authz/src/test/scala/org/apache/kyuubi/plugin/spark/authz/ranger/RangerSparkExtensionSuite.scala
@@ -576,4 +576,49 @@ class HiveCatalogRangerSparkExtensionSuite extends RangerSparkExtensionSuite {
       }
     }
   }
+
+  test("[KYUUBI #3371] support throws all disallowed privileges in exception") {
+    val db1 = "default"
+    val srcTable1 = "hive_src1"
+    val srcTable2 = "hive_src2"
+    val sinkTable1 = "hive_sink1"
+
+    withCleanTmpResources(Seq(
+      (s"$db1.$srcTable1", "table"),
+      (s"$db1.$srcTable2", "table"),
+      (s"$db1.$sinkTable1", "table"))) {
+      doAs(
+        "admin",
+        sql(s"CREATE TABLE IF NOT EXISTS $db1.$srcTable1" +
+          s" (id int, name string, city string)"))
+
+      doAs(
+        "admin",
+        sql(s"CREATE TABLE IF NOT EXISTS $db1.$srcTable2" +
+          s" (id int, age int)"))
+
+      doAs(
+        "admin",
+        sql(s"CREATE TABLE IF NOT EXISTS $db1.$sinkTable1" +
+          s" (id int, age int, name string, city string)"))
+
+      val insertSql1 = s"INSERT INTO $sinkTable1" +
+        s" SELECT tb1.id as id, tb2.age as age, tb1.name as name, tb1.city as city" +
+        s" FROM $db1.$srcTable1 as tb1" +
+        s" JOIN $db1.$srcTable2 as tb2" +
+        s" on tb1.id = tb2.id"
+      val e1 = intercept[AccessControlException](doAs("someone", sql(insertSql1)))
+      assert(e1.getMessage.contains(s"does not have [select] privilege on [$db1/$srcTable1/id]"))
+
+      SparkRangerAdminPlugin.getRangerConf.setBoolean(
+        s"ranger.plugin.${SparkRangerAdminPlugin.getServiceType}.authorize.in.single.call",
+        true)
+      val e2 = intercept[AccessControlException](doAs("someone", sql(insertSql1)))
+      assert(e2.getMessage.contains(s"does not have" +
+        s" [select] privilege on" +
+        s" [$db1/$srcTable1/id,$db1/$srcTable1/name,$db1/$srcTable1/city," +
+        s"$db1/$srcTable2/age,$db1/$srcTable2/id]," +
+        s" [update] privilege on [$db1/$sinkTable1]"))
+    }
+  }
 }