World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14290] fix(spark-connector): Report denied tables from the analyzed plan instead of a thread-local (#14294)
YangJie1a16c0271400
diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/AuthorizationTable.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/AuthorizationTable.javaindex fc5885b2be..5d3e9ffa2f 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/AuthorizationTable.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/AuthorizationTable.java@@ -45,11 +45,13 @@ import org.apache.spark.sql.util.CaseInsensitiveStringMap;* table.** <p>The connector does not load the real Spark table for a denied table, because that load would- * bypass the very authorization the caller is missing. Instead {@link #deny} records the table and- * its required privileges in a per-thread collector and returns this placeholder so Spark's {@code- * ResolveRelations} can finish resolving every relation in the query. {@link- * RequiredPrivilegesCheck} then drains the collector once resolution completes and reports all- * denied tables together, before analysis fails on anything else.+ * bypass the very authorization the caller is missing. Instead {@link #deny} returns this+ * placeholder, which carries the table identifier, the required privileges and the original+ * failure, so Spark's {@code ResolveRelations} can finish resolving the relations of the query.+ * {@link RequiredPrivilegesCheck} then finds the placeholders in the analyzed plan and reports them+ * in one error.+ *+ * <p>Nothing is recorded outside the plan, so a denial cannot fail a later query.** <p>The metadata methods ({@link #name}, {@link #schema}, ...) return harmless placeholders so the* relation can be built during resolution, while the data-access methods ({@link #newScanBuilder},@@ -58,11 +60,6 @@ import org.apache.spark.sql.util.CaseInsensitiveStringMap;*/public class AuthorizationTable implements Table, SupportsRead, SupportsWrite {- // Denied tables discovered while resolving the relations of a single query, keyed by the fully- // qualified table identifier. Held per-thread because Spark analyzes one query per thread.- private static final ThreadLocal<DeniedTables> DENIED_TABLES =- ThreadLocal.withInitial(DeniedTables::new);-private static final StructType EMPTY_SCHEMA = new StructType();private static final Transform[] EMPTY_PARTITIONING = new Transform[0];private static final Set<TableCapability> CAPABILITIES =@@ -74,16 +71,23 @@ public class AuthorizationTable implements Table, SupportsRead, SupportsWrite {TableCapability.OVERWRITE_DYNAMIC);private final String name;+ private final String tableIdentifier;+ private final Set<Privilege.Name> requiredPrivileges;private final ForbiddenException forbiddenException;- private AuthorizationTable(String name, ForbiddenException forbiddenException) {+ private AuthorizationTable(+ String name,+ String tableIdentifier,+ Set<Privilege.Name> requiredPrivileges,+ ForbiddenException forbiddenException) {this.name = name;+ this.tableIdentifier = tableIdentifier;+ this.requiredPrivileges = requiredPrivileges;this.forbiddenException = forbiddenException;}/**- * Records a denied table for the current thread and returns a placeholder table to keep in the- * analyzed plan.+ * Returns a placeholder table carrying the authorization failure, to keep in the analyzed plan.** @param name the simple table name surfaced to Spark* @param tableIdentifier the fully qualified Gravitino table identifier@@ -96,27 +100,55 @@ public class AuthorizationTable implements Table, SupportsRead, SupportsWrite {String tableIdentifier,Set<Privilege.Name> requiredPrivileges,ForbiddenException forbiddenException) {- DENIED_TABLES.get().record(tableIdentifier, requiredPrivileges, forbiddenException);- return new AuthorizationTable(name, forbiddenException);+ return new AuthorizationTable(name, tableIdentifier, requiredPrivileges, forbiddenException);}/**- * Returns an aggregated authorization failure for every denied table collected on the current- * thread, then clears the collector. Returns {@link Optional#empty()} when no table was denied.+ * Aggregates the authorization failures carried by the given denied placeholders into one message+ * listing every table and its required privileges, in table-identifier order.*- * @return the aggregated failure, or empty if there is none+ * @param deniedTables the denied placeholders found in a plan+ * @return the aggregated failure, or empty when nothing was denied*/- public static Optional<ForbiddenException> drainFailure() {- try {- return DENIED_TABLES.get().failure();- } finally {- clear();+ public static Optional<ForbiddenException> aggregateFailure(+ Iterable<AuthorizationTable> deniedTables) {+ Map<String, Set<Privilege.Name>> tables = new TreeMap<>();+ ForbiddenException firstFailure = null;+ for (AuthorizationTable denied : deniedTables) {+ tables+ .computeIfAbsent(denied.tableIdentifier, ignored -> new TreeSet<>())+ .addAll(denied.requiredPrivileges);+ if (firstFailure == null) {+ firstFailure = denied.forbiddenException;+ }}+ if (tables.isEmpty()) {+ return Optional.empty();+ }++ String requirements =+ tables.entrySet().stream()+ .map(+ entry ->+ entry.getKey()+ + ": "+ + entry.getValue().stream()+ .map(Privilege.Name::name)+ .collect(Collectors.joining(", ")))+ .collect(Collectors.joining("; "));+ return Optional.of(+ new ForbiddenException(+ firstFailure, "Missing required privileges for Spark tables: [%s]", requirements));+ }++ /** Returns the fully qualified Gravitino table identifier that was denied. */+ public String tableIdentifier() {+ return tableIdentifier;}- /** Clears the denied tables collected on the current thread. */- public static void clear() {- DENIED_TABLES.remove();+ /** Returns the privileges whose absence denied the table. */+ public Set<Privilege.Name> requiredPrivileges() {+ return requiredPrivileges;}@Override@@ -157,41 +189,4 @@ public class AuthorizationTable implements Table, SupportsRead, SupportsWrite {public WriteBuilder newWriteBuilder(LogicalWriteInfo info) {throw forbiddenException;}-- private static class DeniedTables {- private final Map<String, Set<Privilege.Name>> tables = new TreeMap<>();- private ForbiddenException firstFailure;-- private void record(- String tableIdentifier,- Set<Privilege.Name> requiredPrivileges,- ForbiddenException forbiddenException) {- tables- .computeIfAbsent(tableIdentifier, ignored -> new TreeSet<>())- .addAll(requiredPrivileges);- if (firstFailure == null) {- firstFailure = forbiddenException;- }- }-- private Optional<ForbiddenException> failure() {- if (tables.isEmpty()) {- return Optional.empty();- }-- String requirements =- tables.entrySet().stream()- .map(- entry ->- entry.getKey()- + ": "- + entry.getValue().stream()- .map(Privilege.Name::name)- .collect(Collectors.joining(", ")))- .collect(Collectors.joining("; "));- return Optional.of(- new ForbiddenException(- firstFailure, "Missing required privileges for Spark tables: [%s]", requirements));- }- }}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/RequiredPrivilegesCheck.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/RequiredPrivilegesCheck.javaindex 902e30045e..731fe6055f 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/RequiredPrivilegesCheck.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/authorization/RequiredPrivilegesCheck.java@@ -19,28 +19,71 @@package org.apache.gravitino.spark.connector.authorization;+import java.util.LinkedList;+import java.util.List;import java.util.Optional;import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.spark.sql.catalyst.analysis.NamedRelation;+import org.apache.spark.sql.catalyst.analysis.ResolvedTable;import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;+import org.apache.spark.sql.catalyst.plans.logical.V2WriteCommand;import org.apache.spark.sql.catalyst.rules.Rule;+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2;+import org.apache.spark.sql.connector.catalog.Table;+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation;+import scala.collection.Iterator;/*** A post-hoc resolution rule that reports the tables a query lacks Gravitino privileges for.*- * <p>It runs after Spark's {@code ResolveRelations} has resolved every relation in the query, so- * all denied tables have been collected by {@link AuthorizationTable#deny}, but before {@code- * checkAnalysis} would fail the query for an unrelated reason (such as a column that cannot be- * resolved against a denied table's placeholder schema). This lets a single error list every- * inaccessible table and its required privileges instead of failing on the first one.+ * <p>It runs after Spark's {@code ResolveRelations}, which leaves an {@link AuthorizationTable}+ * placeholder in the plan for each denied table, and before {@code checkAnalysis} would fail the+ * query for an unrelated reason (such as a column that cannot be resolved against a placeholder's+ * empty schema). It lists the denied tables of the plan and their required privileges in one error.+ * A subquery is analyzed separately, so its denied tables are reported on their own.*/public class RequiredPrivilegesCheck extends Rule<LogicalPlan> {@Overridepublic LogicalPlan apply(LogicalPlan plan) {- Optional<ForbiddenException> failure = AuthorizationTable.drainFailure();+ Optional<ForbiddenException> failure = AuthorizationTable.aggregateFailure(collectDenied(plan));if (failure.isPresent()) {throw failure.get();}return plan;}++ private static List<AuthorizationTable> collectDenied(LogicalPlan plan) {+ List<AuthorizationTable> denied = new LinkedList<>();+ collectDenied(plan, denied);+ return denied;+ }++ private static void collectDenied(LogicalPlan plan, List<AuthorizationTable> denied) {+ if (plan instanceof DataSourceV2Relation) {+ addIfDenied(((DataSourceV2Relation) plan).table(), denied);+ } else if (plan instanceof ResolvedTable) {+ // Commands such as DESCRIBE TABLE and SHOW CREATE TABLE resolve their table to this node.+ addIfDenied(((ResolvedTable) plan).table(), denied);+ } else if (plan instanceof StreamingRelationV2) {+ // Streaming sources resolve to this leaf node instead of DataSourceV2Relation.+ addIfDenied(((StreamingRelationV2) plan).table(), denied);+ } else if (plan instanceof V2WriteCommand) {+ // Write commands keep the target relation in their table() field, outside children.+ NamedRelation writeTarget = ((V2WriteCommand) plan).table();+ if (writeTarget instanceof DataSourceV2Relation) {+ addIfDenied(((DataSourceV2Relation) writeTarget).table(), denied);+ }+ }+ Iterator<LogicalPlan> children = plan.children().iterator();+ while (children.hasNext()) {+ collectDenied(children.next(), denied);+ }+ }++ private static void addIfDenied(Table table, List<AuthorizationTable> denied) {+ if (table instanceof AuthorizationTable) {+ denied.add((AuthorizationTable) table);+ }+ }}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.javaindex 21781dc479..17c5f98cf2 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java@@ -684,18 +684,17 @@ public abstract class BaseCatalog implements TableCatalog, SupportsNamespaces, F// Do not load the underlying Spark table here: that load bypasses Gravitino authorization,// which the caller is precisely missing.//- // Unlike the read path, a write command targets a single table, so there is nothing to- // aggregate across relations. Returning an empty-schema placeholder here would let Spark's- // ResolveOutputRelation reject the write with a column-arity error before- // RequiredPrivilegesCheck runs, surfacing the wrong failure and leaving the recorded denial- // on the thread to leak into later queries. Record the denial and surface the aggregated- // authorization failure immediately, which also clears the per-thread collector.- AuthorizationTable.deny(- ident.name(),- String.format("%s.%s.%s", catalogName, getDatabase(ident), ident.name()),- Sets.newHashSet(Privilege.Name.MODIFY_TABLE),- e);- throw AuthorizationTable.drainFailure().orElse(e);+ // Returning an empty-schema placeholder here would let Spark's ResolveOutputRelation reject+ // the write with a column-arity error before RequiredPrivilegesCheck runs, surfacing the+ // wrong failure. Fail now; the error lists only the write target.+ AuthorizationTable denied =+ (AuthorizationTable)+ AuthorizationTable.deny(+ ident.name(),+ String.format("%s.%s.%s", catalogName, getDatabase(ident), ident.name()),+ Sets.newHashSet(Privilege.Name.MODIFY_TABLE),+ e);+ throw AuthorizationTable.aggregateFailure(Collections.singletonList(denied)).orElse(e);}org.apache.spark.sql.connector.catalog.Table sparkTable = loadSparkTable(ident);// Will create a catalog specific tablediff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestAuthorizationTable.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestAuthorizationTable.javadeleted file mode 100644index 38d9a645fe..0000000000--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestAuthorizationTable.java+++ /dev/null@@ -1,101 +0,0 @@-/*- * 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.gravitino.spark.connector.authorization;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertSame;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;--import com.google.common.collect.ImmutableSet;-import java.util.Optional;-import org.apache.gravitino.authorization.Privilege;-import org.apache.gravitino.exceptions.ForbiddenException;-import org.apache.spark.sql.connector.catalog.SupportsRead;-import org.apache.spark.sql.connector.catalog.SupportsWrite;-import org.apache.spark.sql.connector.catalog.Table;-import org.apache.spark.sql.connector.catalog.TableCapability;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.Test;--public class TestAuthorizationTable {-- @AfterEach- void clearCollector() {- AuthorizationTable.clear();- }-- @Test- void testDenyCollectsAndAggregatesDeniedTables() {- ForbiddenException firstCause = new ForbiddenException("denied table_a");- Table table =- AuthorizationTable.deny(- "table_a",- "catalog.schema.table_a",- ImmutableSet.of(Privilege.Name.SELECT_TABLE),- firstCause);- AuthorizationTable.deny(- "table_b",- "catalog.schema.table_b",- ImmutableSet.of(Privilege.Name.MODIFY_TABLE),- new ForbiddenException("denied table_b"));-- assertTrue(table instanceof SupportsRead);- assertTrue(table instanceof SupportsWrite);- assertTrue(table.capabilities().contains(TableCapability.BATCH_READ));- assertTrue(table.capabilities().contains(TableCapability.BATCH_WRITE));-- Optional<ForbiddenException> failure = AuthorizationTable.drainFailure();- assertTrue(failure.isPresent());- assertEquals(- "Missing required privileges for Spark tables: "- + "[catalog.schema.table_a: SELECT_TABLE; catalog.schema.table_b: MODIFY_TABLE]",- failure.get().getMessage());- assertSame(firstCause, failure.get().getCause());-- // The collector is drained, so a subsequent query starts clean.- assertFalse(AuthorizationTable.drainFailure().isPresent());- }-- @Test- void testFailsClosedWhenAccessed() {- ForbiddenException cause = new ForbiddenException("denied");- Table table =- AuthorizationTable.deny(- "table_a",- "catalog.schema.table_a",- ImmutableSet.of(Privilege.Name.SELECT_TABLE),- cause);-- assertSame(- cause,- assertThrows(ForbiddenException.class, () -> ((SupportsRead) table).newScanBuilder(null)));- assertSame(- cause,- assertThrows(- ForbiddenException.class, () -> ((SupportsWrite) table).newWriteBuilder(null)));- }-- @Test- void testDrainFailureEmptyWhenNothingDenied() {- assertFalse(AuthorizationTable.drainFailure().isPresent());- }-}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesCheck.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesCheck.javaindex 73c082206c..6d21bf31ca 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesCheck.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesCheck.java@@ -24,39 +24,53 @@ import static org.junit.jupiter.api.Assertions.assertSame;import static org.junit.jupiter.api.Assertions.assertThrows;import com.google.common.collect.ImmutableSet;+import java.util.Arrays;import org.apache.gravitino.authorization.Privilege;import org.apache.gravitino.exceptions.ForbiddenException;import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;import org.apache.spark.sql.catalyst.plans.logical.OneRowRelation;-import org.junit.jupiter.api.AfterEach;+import org.apache.spark.sql.catalyst.plans.logical.Union;+import org.apache.spark.sql.connector.catalog.SupportsRead;+import org.apache.spark.sql.connector.catalog.SupportsWrite;+import org.apache.spark.sql.connector.catalog.Table;+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation;+import org.apache.spark.sql.util.CaseInsensitiveStringMap;import org.junit.jupiter.api.Test;+import scala.collection.JavaConverters;+@SuppressWarnings("deprecation") // JavaConverters is deprecated on Scala 2.13 but required on 2.12public class TestRequiredPrivilegesCheck {- @AfterEach- void clearCollector() {- AuthorizationTable.clear();+ private static Table denied(+ String tableIdentifier, Privilege.Name first, Privilege.Name... rest) {+ return AuthorizationTable.deny(+ tableIdentifier.substring(tableIdentifier.lastIndexOf('.') + 1),+ tableIdentifier,+ ImmutableSet.<Privilege.Name>builder().add(first).add(rest).build(),+ new ForbiddenException("denied %s", tableIdentifier));+ }++ private static LogicalPlan relation(Table table) {+ return DataSourceV2Relation.create(+ table, scala.Option.empty(), scala.Option.empty(), CaseInsensitiveStringMap.empty());}@Testvoid testReportsAllDeniedTablesInDeterministicOrder() {- AuthorizationTable.deny(- "table_b",- "catalog.schema.table_b",- ImmutableSet.of(Privilege.Name.MODIFY_TABLE),- new ForbiddenException("denied table_b"));- AuthorizationTable.deny(- "table_a",- "catalog.schema.table_a",- ImmutableSet.of(Privilege.Name.SELECT_TABLE),- new ForbiddenException("denied table_a"));- AuthorizationTable.deny(- "table_a",- "catalog.schema.table_a",- ImmutableSet.of(Privilege.Name.MODIFY_TABLE),- new ForbiddenException("denied table_a"));+ LogicalPlan plan =+ new Union(+ JavaConverters.asScalaBuffer(+ Arrays.asList(+ relation(denied("catalog.schema.table_b", Privilege.Name.MODIFY_TABLE)),+ relation(+ denied(+ "catalog.schema.table_a",+ Privilege.Name.MODIFY_TABLE,+ Privilege.Name.SELECT_TABLE))))+ .toList(),+ true,+ true);- LogicalPlan plan = new OneRowRelation();ForbiddenException exception =assertThrows(ForbiddenException.class, () -> new RequiredPrivilegesCheck().apply(plan));@@ -67,6 +81,25 @@ public class TestRequiredPrivilegesCheck {exception.getMessage());}+ @Test+ void testDeniedTableFailsClosedWhenAccessed() {+ ForbiddenException cause = new ForbiddenException("denied");+ Table table =+ AuthorizationTable.deny(+ "table_a",+ "catalog.schema.table_a",+ ImmutableSet.of(Privilege.Name.SELECT_TABLE),+ cause);++ assertSame(+ cause,+ assertThrows(ForbiddenException.class, () -> ((SupportsRead) table).newScanBuilder(null)));+ assertSame(+ cause,+ assertThrows(+ ForbiddenException.class, () -> ((SupportsWrite) table).newWriteBuilder(null)));+ }+@Testvoid testReturnsPlanUnchangedWhenNothingDenied() {LogicalPlan plan = new OneRowRelation();diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesSparkResolution.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesSparkResolution.javaindex 187beaf440..dbc428cc60 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesSparkResolution.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/authorization/TestRequiredPrivilegesSparkResolution.java@@ -19,7 +19,7 @@package org.apache.gravitino.spark.connector.authorization;-import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;@@ -37,7 +37,6 @@ import org.apache.spark.sql.internal.StaticSQLConf;import org.apache.spark.sql.types.StructType;import org.apache.spark.sql.util.CaseInsensitiveStringMap;import org.junit.jupiter.api.AfterAll;-import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;@@ -61,6 +60,7 @@ public class TestRequiredPrivilegesSparkResolution {.appName("test-authorization-resolution").config("spark.ui.enabled", "false").config("spark.sql.catalog.denied", DeniedTableCatalog.class.getName())+ .config("spark.sql.catalog.broken", BrokenTableCatalog.class.getName()).config(StaticSQLConf.SPARK_SESSION_EXTENSIONS().key(),GravitinoAuthorizationSparkSessionExtensions.class.getName())@@ -72,12 +72,6 @@ public class TestRequiredPrivilegesSparkResolution {if (spark != null) {spark.stop();}- AuthorizationTable.clear();- }-- @AfterEach- void clearCollector() {- AuthorizationTable.clear();}@Test@@ -117,16 +111,44 @@ public class TestRequiredPrivilegesSparkResolution {}@Test- void testSqlParserClearsStaleDeniedTablesBeforeNextQuery() throws Exception {- AuthorizationTable.deny(- "stale_table",- "catalog.schema.stale_table",- ImmutableSet.of(Privilege.Name.SELECT_TABLE),- new ForbiddenException("denied stale table"));+ void testDescribeDeniedTableReportsForbidden() {+ ForbiddenException failure =+ assertThrows(ForbiddenException.class, () -> spark.sql("DESCRIBE TABLE denied.db.t1"));++ assertTrue(failure.getMessage().contains("denied.db.t1: SELECT_TABLE"), failure.getMessage());+ }++ @Test+ void testSubqueryOnDeniedTableReportsForbidden() {+ ForbiddenException failure =+ assertThrows(+ ForbiddenException.class,+ () -> spark.sql("SELECT 1 WHERE EXISTS (SELECT 1 FROM denied.db.t1)"));++ assertTrue(failure.getMessage().contains("denied.db.t1: SELECT_TABLE"), failure.getMessage());+ }++ @Test+ void testDeniedGetTableDoesNotFailLaterQueries() throws Exception {+ // Spark 3.5 loads the table after analysis, so no post-hoc rule sees the denied placeholder.+ // Spark 4 resolves the table during analysis and reports the denial there.+ try {+ spark.catalog().getTable("denied.db.t1");+ } catch (ForbiddenException e) {+ assertTrue(e.getMessage().contains("denied.db.t1: SELECT_TABLE"), e.getMessage());+ }- spark.sessionState().sqlParser().parsePlan("SELECT 1");+ assertEquals(1L, spark.range(1).count());+ }++ @Test+ void testAbortedAnalysisDoesNotFailLaterQueries() {+ // The broken catalog throws while the join is resolved, after denied.db.t1 was loaded.+ assertThrows(+ RuntimeException.class,+ () -> spark.sql("SELECT 1 FROM denied.db.t1 JOIN broken.db.t2 ON 1 = 1"));- assertFalse(AuthorizationTable.drainFailure().isPresent());+ assertEquals(1L, spark.range(1).count());}/** A catalog that denies every table, used to exercise the authorization resolution path. */@@ -184,4 +206,54 @@ public class TestRequiredPrivilegesSparkResolution {throw new UnsupportedOperationException();}}++ /** A catalog whose loads blow up mid-resolution, to abort an analysis after a denial. */+ public static class BrokenTableCatalog implements TableCatalog {++ private String name;++ @Override+ public void initialize(String name, CaseInsensitiveStringMap options) {+ this.name = name;+ }++ @Override+ public String name() {+ return name;+ }++ @Override+ public Table loadTable(Identifier ident) {+ throw new IllegalStateException("catalog unavailable");+ }++ @Override+ public Identifier[] listTables(String[] namespace) {+ return new Identifier[0];+ }++ @Override+ // Overriding the form deprecated in Spark 3.4 keeps this stub compiling on every supported+ // version; the test never calls it.+ @SuppressWarnings("deprecation")+ public Table createTable(+ Identifier ident, StructType schema, Transform[] partitions, Map<String, String> props) {+ throw new UnsupportedOperationException();+ }++ @Override+ public Table alterTable(Identifier ident, TableChange... changes) {+ throw new UnsupportedOperationException();+ }++ @Override+ public boolean dropTable(Identifier ident) {+ return false;+ }++ @Override+ public void renameTable(Identifier oldIdent, Identifier newIdent) {+ throw new UnsupportedOperationException();+ }+ }}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogAuthorization.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogAuthorization.javaindex 35668e1eae..884f75f0d8 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogAuthorization.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogAuthorization.java@@ -19,7 +19,9 @@package org.apache.gravitino.spark.connector.catalog;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.mock;@@ -30,7 +32,6 @@ import com.google.common.collect.ImmutableSet;import java.lang.reflect.Field;import java.time.OffsetDateTime;import java.util.Map;-import java.util.Optional;import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.Privilege;@@ -53,7 +54,6 @@ import org.apache.spark.sql.internal.SQLConf;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.util.CaseInsensitiveStringMap;import org.junit.jupiter.api.AfterAll;-import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;@@ -95,11 +95,6 @@ public class TestBaseCatalogAuthorization {converter.set(catalog, new SparkTableChangeConverter(new SparkTypeConverter()));}- @AfterEach- void clearDeniedTables() {- AuthorizationTable.clear();- }-@Testvoid testLoadTablePassesSelectTablePrivilege() throws Exception {Identifier identifier = Identifier.of(new String[] {"schema"}, "table_a");@@ -127,12 +122,30 @@ public class TestBaseCatalogAuthorization {Table result = catalog.loadTable(identifier);- // The underlying Spark table is never loaded for a denied table; a placeholder is returned and- // the required privileges are collected for RequiredPrivilegesCheck to report during analysis.+ // The underlying Spark table is never loaded for a denied table; a placeholder carrying the+ // failure is returned for RequiredPrivilegesCheck to find in the analyzed plan.assertTrue(result instanceof AuthorizationTable);- Optional<ForbiddenException> failure = AuthorizationTable.drainFailure();- assertTrue(failure.isPresent());- assertTrue(failure.get().getMessage().contains("table_a: SELECT_TABLE"));+ AuthorizationTable deniedTable = (AuthorizationTable) result;+ assertEquals("null.schema.table_a", deniedTable.tableIdentifier());+ assertEquals(ImmutableSet.of(Privilege.Name.SELECT_TABLE), deniedTable.requiredPrivileges());+ }++ @Test+ void testDeniedWriteReportsTheWriteTarget() throws Exception {+ Identifier identifier = Identifier.of(new String[] {"schema"}, "table_a");+ NameIdentifier gravitinoIdentifier = NameIdentifier.of("schema", "table_a");+ ForbiddenException original = new ForbiddenException("denied write");+ when(gravitinoTableCatalog.loadTable(+ eq(gravitinoIdentifier), eq(ImmutableSet.of(Privilege.Name.MODIFY_TABLE))))+ .thenThrow(original);++ ForbiddenException thrown =+ assertThrows(ForbiddenException.class, () -> catalog.loadForWriting(identifier));++ assertEquals(+ "Missing required privileges for Spark tables: [null.schema.table_a: MODIFY_TABLE]",+ thrown.getMessage());+ assertSame(original, thrown.getCause());}@Testdiff --git a/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java b/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.javaindex fbdaeb9ce1..8dce471b30 100644--- a/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java+++ b/spark-connector/v3.5/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java@@ -20,77 +20,22 @@package org.apache.gravitino.spark.connector.authorization;import org.apache.spark.sql.SparkSessionExtensions;-import org.apache.spark.sql.catalyst.FunctionIdentifier;-import org.apache.spark.sql.catalyst.TableIdentifier;-import org.apache.spark.sql.catalyst.expressions.Expression;-import org.apache.spark.sql.catalyst.parser.ParseException;-import org.apache.spark.sql.catalyst.parser.ParserInterface;-import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;-import org.apache.spark.sql.types.DataType;-import org.apache.spark.sql.types.StructType;import scala.Function1;-import scala.collection.immutable.Seq;-/** Registers Gravitino authorization checks with a Spark session. */+/**+ * Registers Gravitino authorization checks with a Spark session.+ *+ * <p>Post-hoc resolution runs after every relation is resolved but before checkAnalysis, so all+ * denied tables are reported together rather than failing on the first resolution error. The+ * denials are read from the analyzed plan itself, so no session state is carried between queries+ * and no parser wrapper is needed.+ */public class GravitinoAuthorizationSparkSessionExtensionsimplements Function1<SparkSessionExtensions, Void> {@Overridepublic Void apply(SparkSessionExtensions extensions) {- // Post-hoc resolution runs after every relation is resolved but before checkAnalysis, so all- // denied tables are reported together rather than failing on the first resolution error.extensions.injectPostHocResolutionRule(session -> new RequiredPrivilegesCheck());- extensions.injectParser((session, parser) -> new AuthorizationParser(parser));return null;}-- private static class AuthorizationParser implements ParserInterface {- private final ParserInterface delegate;-- private AuthorizationParser(ParserInterface delegate) {- this.delegate = delegate;- }-- @Override- public LogicalPlan parsePlan(String sqlText) throws ParseException {- AuthorizationTable.clear();- return delegate.parsePlan(sqlText);- }-- @Override- public Expression parseExpression(String sqlText) throws ParseException {- return delegate.parseExpression(sqlText);- }-- @Override- public TableIdentifier parseTableIdentifier(String sqlText) throws ParseException {- return delegate.parseTableIdentifier(sqlText);- }-- @Override- public FunctionIdentifier parseFunctionIdentifier(String sqlText) throws ParseException {- return delegate.parseFunctionIdentifier(sqlText);- }-- @Override- public Seq<String> parseMultipartIdentifier(String sqlText) throws ParseException {- return delegate.parseMultipartIdentifier(sqlText).toList();- }-- @Override- public LogicalPlan parseQuery(String sqlText) throws ParseException {- AuthorizationTable.clear();- return delegate.parseQuery(sqlText);- }-- @Override- public StructType parseTableSchema(String sqlText) throws ParseException {- return delegate.parseTableSchema(sqlText);- }-- @Override- public DataType parseDataType(String sqlText) throws ParseException {- return delegate.parseDataType(sqlText);- }- }}diff --git a/spark-connector/v4.0/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java b/spark-connector/v4.0/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.javaindex c466dd8f23..8dce471b30 100644--- a/spark-connector/v4.0/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java+++ b/spark-connector/v4.0/spark/src/main/java/org/apache/gravitino/spark/connector/authorization/GravitinoAuthorizationSparkSessionExtensions.java@@ -20,89 +20,22 @@package org.apache.gravitino.spark.connector.authorization;import org.apache.spark.sql.SparkSessionExtensions;-import org.apache.spark.sql.catalyst.FunctionIdentifier;-import org.apache.spark.sql.catalyst.TableIdentifier;-import org.apache.spark.sql.catalyst.expressions.Expression;-import org.apache.spark.sql.catalyst.parser.ParseException;-import org.apache.spark.sql.catalyst.parser.ParserInterface;-import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;-import org.apache.spark.sql.types.DataType;-import org.apache.spark.sql.types.StructType;import scala.Function1;-import scala.collection.immutable.Seq;/*** Registers Gravitino authorization checks with a Spark session.*- * <p>This is the Spark 4 copy. Each version module carries one at this name, because Spark 4 added- * the abstract {@code parseRoutineParam} method to {@code ParserInterface} and a parser can only- * implement one version's interface. Everything else here matches the Spark 3.5 copy in {@code- * v3.5/spark}.+ * <p>Post-hoc resolution runs after every relation is resolved but before checkAnalysis, so all+ * denied tables are reported together rather than failing on the first resolution error. The+ * denials are read from the analyzed plan itself, so no session state is carried between queries+ * and no parser wrapper is needed.*/public class GravitinoAuthorizationSparkSessionExtensionsimplements Function1<SparkSessionExtensions, Void> {@Overridepublic Void apply(SparkSessionExtensions extensions) {- // Post-hoc resolution runs after every relation is resolved but before checkAnalysis, so all- // denied tables are reported together rather than failing on the first resolution error.extensions.injectPostHocResolutionRule(session -> new RequiredPrivilegesCheck());- extensions.injectParser((session, parser) -> new AuthorizationParser(parser));return null;}-- private static class AuthorizationParser implements ParserInterface {- private final ParserInterface delegate;-- private AuthorizationParser(ParserInterface delegate) {- this.delegate = delegate;- }-- @Override- public LogicalPlan parsePlan(String sqlText) throws ParseException {- AuthorizationTable.clear();- return delegate.parsePlan(sqlText);- }-- @Override- public Expression parseExpression(String sqlText) throws ParseException {- return delegate.parseExpression(sqlText);- }-- @Override- public TableIdentifier parseTableIdentifier(String sqlText) throws ParseException {- return delegate.parseTableIdentifier(sqlText);- }-- @Override- public FunctionIdentifier parseFunctionIdentifier(String sqlText) throws ParseException {- return delegate.parseFunctionIdentifier(sqlText);- }-- @Override- public Seq<String> parseMultipartIdentifier(String sqlText) throws ParseException {- return delegate.parseMultipartIdentifier(sqlText).toList();- }-- @Override- public LogicalPlan parseQuery(String sqlText) throws ParseException {- AuthorizationTable.clear();- return delegate.parseQuery(sqlText);- }-- @Override- public StructType parseTableSchema(String sqlText) throws ParseException {- return delegate.parseTableSchema(sqlText);- }-- @Override- public DataType parseDataType(String sqlText) throws ParseException {- return delegate.parseDataType(sqlText);- }-- @Override- public StructType parseRoutineParam(String sqlText) throws ParseException {- return delegate.parseRoutineParam(sqlText);- }- }}