World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#9970] feat(iceberg): Iceberg REST supports the hierarchical schema (#11118)
roryqiaf7dd67b4db4
diff --git a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java b/api/src/main/java/org/apache/gravitino/authorization/Privileges.javaindex c44d251a10..393252cf15 100644--- a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java+++ b/api/src/main/java/org/apache/gravitino/authorization/Privileges.java@@ -501,7 +501,7 @@ public class Privileges {@Overridepublic boolean canBindTo(MetadataObject.Type type) {- return type == MetadataObject.Type.METALAKE || type == MetadataObject.Type.CATALOG;+ return SCHEMA_SUPPORTED_TYPES.contains(type);}}diff --git a/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java b/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.javaindex 22050f6c80..061f421fe7 100644--- a/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java+++ b/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java@@ -238,7 +238,7 @@ public class TestSecurableObjects {// Test create schemaAssertions.assertTrue(createSchema.canBindTo(MetadataObject.Type.METALAKE));Assertions.assertTrue(createSchema.canBindTo(MetadataObject.Type.CATALOG));- Assertions.assertFalse(createSchema.canBindTo(MetadataObject.Type.SCHEMA));+ Assertions.assertTrue(createSchema.canBindTo(MetadataObject.Type.SCHEMA));Assertions.assertFalse(createSchema.canBindTo(MetadataObject.Type.TABLE));Assertions.assertFalse(createSchema.canBindTo(MetadataObject.Type.TOPIC));Assertions.assertFalse(createSchema.canBindTo(MetadataObject.Type.FILESET));diff --git a/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerAuthorizationPluginIT.java b/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerAuthorizationPluginIT.javaindex 41e91008c8..0f16927bc7 100644--- a/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerAuthorizationPluginIT.java+++ b/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerAuthorizationPluginIT.java@@ -268,6 +268,14 @@ public class RangerAuthorizationPluginIT {rangerAuthPlugin.validAuthorizationOperation(Arrays.asList(createSchemaInMetalake, createSchemaInCatalog)));+ SecurableObject createSchemaOnSchema =+ SecurableObjects.parse(+ "catalog.schema",+ MetadataObject.Type.SCHEMA,+ Lists.newArrayList(Privileges.CreateSchema.allow()));+ Assertions.assertTrue(+ rangerAuthPlugin.validAuthorizationOperation(Arrays.asList(createSchemaOnSchema)));+// Use schema operationSecurableObject useSchema =SecurableObjects.parse(@@ -551,13 +559,6 @@ public class RangerAuthorizationPluginIT {rangerAuthPlugin.validAuthorizationOperation(Arrays.asList(useCatalog2)));// Schema- SecurableObject createSchema1 =- SecurableObjects.parse(- String.format("catalog.schema"),- MetadataObject.Type.SCHEMA,- Lists.newArrayList(Privileges.CreateSchema.allow()));- Assertions.assertFalse(- rangerAuthPlugin.validAuthorizationOperation(Arrays.asList(createSchema1)));SecurableObject createSchema2 =SecurableObjects.parse(String.format("catalog.schema.table"),diff --git a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.javaindex 0449acbfd8..59a83b8e85 100644--- a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java+++ b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java@@ -1893,6 +1893,18 @@ public class CatalogMysqlIT extends BaseIT {});}+ @Test+ void testListSchemaWithDotInMysqlUnderlyingDatabaseName() {+ String schemaWithDot = GravitinoITUtils.genRandomName("db") + ".nested";+ String sql = String.format("CREATE DATABASE `%s`", schemaWithDot);+ mysqlService.executeQuery(sql);++ String[] schemas = catalog.asSchemas().listSchemas();+ Assertions.assertTrue(+ Arrays.asList(schemas).contains(schemaWithDot),+ "Schema with dot in MySQL should be listed as logical schema name");+ }+@Testvoid testMySQLSchemaNameCaseSensitive() {Column col1 = Column.of("col_1", Types.LongType.get(), "id", false, false, null);diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/ops/IcebergCatalogWrapperHelper.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/ops/IcebergCatalogWrapperHelper.javaindex 28ea5eafc4..808a830651 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/ops/IcebergCatalogWrapperHelper.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/ops/IcebergCatalogWrapperHelper.java@@ -30,6 +30,7 @@ import java.util.Set;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.lakehouse.iceberg.converter.IcebergDataTypeConverter;import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper.IcebergTableChange;+import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.TableChange.AddColumn;import org.apache.gravitino.rel.TableChange.After;@@ -44,6 +45,7 @@ import org.apache.gravitino.rel.TableChange.UpdateColumnComment;import org.apache.gravitino.rel.TableChange.UpdateColumnPosition;import org.apache.gravitino.rel.TableChange.UpdateColumnType;import org.apache.gravitino.rel.TableChange.UpdateComment;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.Schema;import org.apache.iceberg.Table;import org.apache.iceberg.Transaction;@@ -231,10 +233,7 @@ public class IcebergCatalogWrapperHelper {public IcebergTableChange buildIcebergTableChanges(NameIdentifier gravitinoNameIdentifier, TableChange... tableChanges) {- TableIdentifier icebergTableIdentifier =- TableIdentifier.of(- Namespace.of(gravitinoNameIdentifier.namespace().levels()),- gravitinoNameIdentifier.name());+ TableIdentifier icebergTableIdentifier = buildIcebergTableIdentifier(gravitinoNameIdentifier);List<ColumnChange> gravitinoColumnChanges = Lists.newArrayList();List<TableChange> gravitinoPropertyChanges = Lists.newArrayList();@@ -292,12 +291,23 @@ public class IcebergCatalogWrapperHelper {}public static Namespace getIcebergNamespace(String... level) {+ // A lone string is a logical schema name that may still be joined by the separator (e.g.+ // "A:B:C"), so it must be split; a multi-element array has already been pre-split into levels.+ if (level.length == 1) {+ return IcebergIdentifierUtils.getIcebergNamespaceFromSchemaName(+ level[0], HierarchicalSchemaUtil.schemaSeparator());+ }return Namespace.of(level);}/**- * Gravitino only supports tables managed with a single level hierarchy, such as- * `{namespace}.{table}`, so we need to perform truncation here.+ * Builds an Iceberg {@link TableIdentifier} from a Gravitino namespace and table name.+ *+ * <p>The last level of the Gravitino namespace is the schema name. When HierarchicalSchema is+ * enabled, that schema name may encode multiple Iceberg namespace levels joined by the configured+ * external separator (e.g. {@code "schema:nested"} → Iceberg namespace {@code ("schema",+ * "nested")}); split it back into a multi-level namespace so the underlying Iceberg catalog+ * receives the correct identifier.** @param namespace The Gravitino name space* @param name The table name@@ -306,19 +316,22 @@ public class IcebergCatalogWrapperHelper {public static TableIdentifier buildIcebergTableIdentifier(org.apache.gravitino.Namespace namespace, String name) {String[] levels = namespace.levels();- return TableIdentifier.of(levels[levels.length - 1], name);+ return TableIdentifier.of(getIcebergNamespace(levels[levels.length - 1]), name);}/**- * Gravitino only supports tables managed with a single level hierarchy, such as- * `{namespace}.{table}`, so we need to perform truncation here.+ * Builds an Iceberg {@link TableIdentifier} from a Gravitino {@link NameIdentifier}.+ *+ * <p>See {@link #buildIcebergTableIdentifier(org.apache.gravitino.Namespace, String)} for how the+ * trailing schema name is converted back into a multi-level Iceberg namespace.** @param nameIdentifier GravitinoNameIdentifier* @return Iceberg TableIdentifier*/public static TableIdentifier buildIcebergTableIdentifier(NameIdentifier nameIdentifier) {String[] levels = nameIdentifier.namespace().levels();- return TableIdentifier.of(levels[levels.length - 1], nameIdentifier.name());+ return TableIdentifier.of(+ getIcebergNamespace(levels[levels.length - 1]), nameIdentifier.name());}@VisibleForTestingdiff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerDispatcher.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerDispatcher.javaindex b78c278783..4257f16dff 100644--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerDispatcher.java@@ -19,6 +19,8 @@package org.apache.gravitino.authorization;+import com.google.common.base.Preconditions;+import java.util.List;import java.util.Optional;import org.apache.gravitino.MetadataObject;@@ -36,6 +38,36 @@ public interface OwnerDispatcher {void setOwner(String metalake, MetadataObject metadataObject, String ownerName, Owner.Type ownerType);+ /**+ * Sets the same owner on multiple metadata objects in iteration order. Semantics match repeated+ * {@link #setOwner} calls; relational {@link org.apache.gravitino.EntityStore} implementations+ * may persist using {@link org.apache.gravitino.SupportsRelationOperations#batchInsertRelations}.+ * The default implementation delegates per object so implementations that wrap {@code setOwner}+ * (e.g. for events) apply consistently.+ *+ * <p>Note: implementations that persist via {@code batchInsertRelations} (such as {@link+ * OwnerManager}) require all {@code metadataObjects} to share the same {@link+ * MetadataObject.Type} within a single call, because the batch operation takes a single object+ * type. Such implementations throw {@link IllegalArgumentException} when mixed types are+ * supplied, so callers should group objects by type before calling. The default per-object+ * implementation has no such restriction.+ *+ * @param metalake the name of the metalake+ * @param metadataObjects the objects to update; must not be null (may be empty)+ * @param ownerName the name of the owner+ * @param ownerType the type of the owner (e.g., USER, GROUP)+ */+ default void setOwners(+ String metalake,+ List<MetadataObject> metadataObjects,+ String ownerName,+ Owner.Type ownerType) {+ Preconditions.checkArgument(metadataObjects != null, "metadataObjects must not be null");+ for (MetadataObject metadataObject : metadataObjects) {+ setOwner(metalake, metadataObject, ownerName, ownerType);+ }+ }+/*** Retrieves the owner of a metadata object.*diff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerEventManager.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerEventManager.javaindex 71a1f611cc..734bcaa4ca 100644--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerEventManager.java+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerEventManager.java@@ -20,6 +20,9 @@package org.apache.gravitino.authorization;import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.List;import java.util.Optional;import lombok.Getter;import org.apache.gravitino.MetadataObject;@@ -67,6 +70,43 @@ public class OwnerEventManager implements OwnerDispatcher {}}+ @Override+ public void setOwners(+ String metalake,+ List<MetadataObject> metadataObjects,+ String ownerName,+ Owner.Type ownerType) {+ Preconditions.checkArgument(metadataObjects != null, "metadataObjects must not be null");+ if (metadataObjects.isEmpty()) {+ return;+ }+ String user = PrincipalUtils.getCurrentUserName();+ OwnerInfo ownerInfo = new OwnerInfo(ownerName, ownerType);+ List<NameIdentifier> identifiers = new ArrayList<>(metadataObjects.size());+ for (MetadataObject metadataObject : metadataObjects) {+ NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);+ identifiers.add(identifier);+ eventBus.dispatchEvent(+ new SetOwnerPreEvent(user, identifier, ownerInfo, metadataObject.type()));+ }+ try {+ ownerDispatcher.setOwners(metalake, metadataObjects, ownerName, ownerType);+ for (int i = 0; i < metadataObjects.size(); i++) {+ MetadataObject metadataObject = metadataObjects.get(i);+ eventBus.dispatchEvent(+ new SetOwnerEvent(user, identifiers.get(i), ownerInfo, metadataObject.type()));+ }+ } catch (Exception e) {+ for (int i = 0; i < metadataObjects.size(); i++) {+ MetadataObject metadataObject = metadataObjects.get(i);+ eventBus.dispatchEvent(+ new SetOwnerFailureEvent(+ user, identifiers.get(i), e, ownerInfo, metadataObject.type()));+ }+ throw e;+ }+ }+@Overridepublic Optional<Owner> getOwner(String metalake, MetadataObject metadataObject) {NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);diff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.javaindex 9e17ef64ec..455bba6a67 100644--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java@@ -18,9 +18,12 @@*/package org.apache.gravitino.authorization;+import com.google.common.base.Preconditions;import java.io.IOException;+import java.util.ArrayList;import java.util.List;import java.util.Optional;+import java.util.stream.Collectors;import javax.annotation.Nullable;import lombok.Getter;import org.apache.gravitino.Entity;@@ -135,6 +138,98 @@ public class OwnerManager implements OwnerDispatcher {}}+ @Override+ public void setOwners(+ String metalake,+ List<MetadataObject> metadataObjects,+ String ownerName,+ Owner.Type ownerType) {+ Preconditions.checkArgument(metadataObjects != null, "metadataObjects must not be null");+ if (metadataObjects.isEmpty()) {+ return;+ }++ List<Optional<Owner>> originOwners = new ArrayList<>(metadataObjects.size());+ for (MetadataObject mo : metadataObjects) {+ originOwners.add(getOwner(metalake, mo));+ }++ Entity.EntityType objectType = MetadataObjectUtil.toEntityType(metadataObjects.get(0));+ for (int i = 1; i < metadataObjects.size(); i++) {+ Preconditions.checkArgument(+ MetadataObjectUtil.toEntityType(metadataObjects.get(i)) == objectType,+ "All metadata objects in setOwners must share the same type");+ }+ List<NameIdentifier> owned =+ metadataObjects.stream()+ .map(mo -> MetadataObjectUtil.toEntityIdent(metalake, mo))+ .collect(Collectors.toList());++ OwnerImpl newOwner = new OwnerImpl();+ NameIdentifier ownerIdent;+ Entity.EntityType ownerEntityType;+ if (ownerType == Owner.Type.USER) {+ ownerIdent = AuthorizationUtils.ofUser(metalake, ownerName);+ ownerEntityType = Entity.EntityType.USER;+ newOwner.name = ownerName;+ newOwner.type = Owner.Type.USER;+ } else if (ownerType == Owner.Type.GROUP) {+ ownerIdent = AuthorizationUtils.ofGroup(metalake, ownerName);+ ownerEntityType = Entity.EntityType.GROUP;+ newOwner.name = ownerName;+ newOwner.type = Owner.Type.GROUP;+ } else {+ throw new IllegalArgumentException("Unsupported owner type: " + ownerType);+ }++ try {+ TreeLockUtils.doWithTreeLock(+ ownerIdent,+ LockType.READ,+ () -> {+ store+ .relationOperations()+ .batchInsertRelations(+ SupportsRelationOperations.Type.OWNER_REL,+ owned,+ objectType,+ ownerIdent,+ ownerEntityType,+ true);+ return null;+ });++ // Owner relations are already persisted; a failure for one plugin notification must not+ // abort the remaining notifications and leave the batch half-notified.+ for (int i = 0; i < metadataObjects.size(); i++) {+ MetadataObject mo = metadataObjects.get(i);+ Optional<Owner> originOwner = originOwners.get(i);+ try {+ AuthorizationUtils.callAuthorizationPluginForMetadataObject(+ metalake,+ mo,+ authorizationPlugin ->+ authorizationPlugin.onOwnerSet(mo, originOwner.orElse(null), newOwner));+ originOwner.ifPresent(owner -> notifyOwnerChange(owner, metalake, mo));+ } catch (RuntimeException re) {+ LOG.warn(+ "Failed to notify authorization plugin for metadata object {} during batch setOwners",+ mo.fullName(),+ re);+ }+ }+ } catch (NoSuchEntityException nse) {+ LOG.warn(+ "Metadata object or owner {} not found for batch setOwners: {}",+ ownerName,+ nse.getMessage());+ throw new NotFoundException(nse, "Metadata object or owner %s is not found", ownerName);+ } catch (IOException ioe) {+ LOG.warn("Fail to batch set owner {} on {} objects", ownerName, metadataObjects.size(), ioe);+ throw new RuntimeException(ioe);+ }+ }+private void notifyOwnerChange(@Nullable Owner oldOwner, String metalake, MetadataObject metadataObject) {GravitinoAuthorizer gravitinoAuthorizer = GravitinoEnv.getInstance().gravitinoAuthorizer();diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergIdentifierUtils.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergIdentifierUtils.javaindex f90b0b0999..a0d21e0356 100644--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergIdentifierUtils.java+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergIdentifierUtils.java@@ -18,22 +18,62 @@*/package org.apache.gravitino.iceberg.common.utils;+import com.google.common.base.Preconditions;+import java.util.regex.Pattern;import org.apache.gravitino.NameIdentifier;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;public class IcebergIdentifierUtils {public static NameIdentifier toGravitinoTableIdentifier(- String metalake, String catalogName, TableIdentifier icebergTableIdentifier) {- return NameIdentifier.of(- metalake,- catalogName,- icebergTableIdentifier.namespace().level(0),- icebergTableIdentifier.name());+ String metalake,+ String catalogName,+ TableIdentifier icebergTableIdentifier,+ String separator) {+ String schemaName = String.join(separator, icebergTableIdentifier.namespace().levels());+ return NameIdentifier.of(metalake, catalogName, schemaName, icebergTableIdentifier.name());}public static NameIdentifier toGravitinoSchemaIdentifier(- String metalake, String catalogName, Namespace icebergNamespace) {- return NameIdentifier.of(metalake, catalogName, icebergNamespace.level(0));+ String metalake, String catalogName, Namespace icebergNamespace, String separator) {+ String schemaName = String.join(separator, icebergNamespace.levels());+ return NameIdentifier.of(metalake, catalogName, schemaName);+ }++ /**+ * Converts a logical Gravitino schema name to an Iceberg {@link Namespace} using the given+ * external separator.+ *+ * <p>The name is split on the separator into a multi-level namespace (e.g. {@code "A:B:C"} with+ * {@code ":"} → {@code Namespace.of("A","B","C")}). Flat names without the separator become a+ * single-level namespace.+ *+ * @param schemaName the logical schema name using the configured external separator+ * @param separator the external namespace separator configured on the server+ * @return the corresponding Iceberg multi-level namespace+ */+ public static Namespace getIcebergNamespaceFromSchemaName(String schemaName, String separator) {+ return Namespace.of(schemaName.split(Pattern.quote(separator), -1));+ }++ /**+ * Converts an Iceberg multi-level {@link Namespace} to a schema name string joined by the given+ * separator.+ *+ * <p>Examples:+ *+ * <ul>+ * <li>{@code Namespace.of("A","B","C")} + {@code ":"} → {@code "A:B:C"} (logical)+ * </ul>+ *+ * @param namespace the Iceberg namespace, which must not be empty+ * @param separator the separator to join levels with+ * @return the joined schema name+ * @throws IllegalArgumentException if the namespace is empty+ */+ public static String icebergNamespaceToSchemaName(Namespace namespace, String separator) {+ Preconditions.checkArgument(+ !namespace.isEmpty(), "Iceberg namespace must not be empty to build a schema name");+ return String.join(separator, namespace.levels());}}diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergIdentifierUtils.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergIdentifierUtils.javaindex 4f609a5860..15d11c1a5b 100644--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergIdentifierUtils.java+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergIdentifierUtils.java@@ -32,7 +32,7 @@ class TestIcebergIdentifierUtils {TableIdentifier icebergTableIdentifier = TableIdentifier.of(Namespace.of("db"), "table");NameIdentifier result =IcebergIdentifierUtils.toGravitinoTableIdentifier(- "metalake", "catalog", icebergTableIdentifier);+ "metalake", "catalog", icebergTableIdentifier, ":");assertEquals("metalake", result.namespace().level(0));assertEquals("catalog", result.namespace().level(1));@@ -40,14 +40,37 @@ class TestIcebergIdentifierUtils {assertEquals("table", result.name());}+ @Test+ void toGravitinoTableIdentifierNestedNamespaceConvertsCorrectly() {+ TableIdentifier icebergTableIdentifier =+ TableIdentifier.of(Namespace.of("A", "B", "C"), "table");+ NameIdentifier result =+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ "metalake", "catalog", icebergTableIdentifier, ":");++ assertEquals("A:B:C", result.namespace().level(2));+ assertEquals("table", result.name());+ }+@Testvoid toGravitinoSchemaIdentifierConvertsCorrectly() {Namespace icebergNamespace = Namespace.of("db");NameIdentifier result =- IcebergIdentifierUtils.toGravitinoSchemaIdentifier("metalake", "catalog", icebergNamespace);+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ "metalake", "catalog", icebergNamespace, ":");assertEquals("metalake", result.namespace().level(0));assertEquals("catalog", result.namespace().level(1));assertEquals("db", result.name());}++ @Test+ void toGravitinoSchemaIdentifierNestedNamespaceConvertsCorrectly() {+ Namespace icebergNamespace = Namespace.of("A", "B", "C");+ NameIdentifier result =+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ "metalake", "catalog", icebergNamespace, ":");++ assertEquals("A:B:C", result.name());+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.javaindex 59a3c4756b..29147d50a8 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java@@ -18,16 +18,25 @@*/package org.apache.gravitino.iceberg.service.dispatcher;+import com.google.common.collect.Lists;import java.io.IOException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.regex.Pattern;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.SchemaDispatcher;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;import org.apache.gravitino.listener.api.event.IcebergRequestContext;+import org.apache.gravitino.lock.LockType;+import org.apache.gravitino.lock.TreeLockUtils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;@@ -58,21 +67,66 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation@Overridepublic CreateNamespaceResponse createNamespace(IcebergRequestContext context, CreateNamespaceRequest createRequest) {- CreateNamespaceResponse response = dispatcher.createNamespace(context, createRequest);-- // Import is intentionally NOT wrapped in try-catch: if it fails the namespace exists in- // Iceberg but not in Gravitino, and silently swallowing that would mislead callers into- // thinking the entity is registered. Surface the failure so the caller can react.- importSchema(context.catalogName(), createRequest.namespace());-- IcebergOwnershipUtils.setSchemaOwner(+ String catalogName = context.catalogName();+ Namespace leaf = createRequest.namespace();+ List<Namespace> newlyOwned = new ArrayList<>();+ // Lock the top-level branch root rather than the whole catalog: any race on shared ancestor+ // ownership has to share leaf.level(0), so serializing per top-level branch is sufficient+ // and lets disjoint branches (e.g. A:... and X:...) create in parallel.+ CreateNamespaceResponse createNamespaceResponse =+ TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(metalake, catalogName, leaf.level(0)),+ LockType.WRITE,+ () -> {+ // Pre-probe so we only claim ownership of truly-new ancestors, never overwriting+ // an existing parent's owner.+ newlyOwned.addAll(getMissingAncestors(context, leaf));+ return dispatcher.createNamespace(context, createRequest);+ });+ // SchemaMetaService.insertSchema splits the leaf's logical name and auto-creates a+ // Gravitino entity row for each ancestor, so a single leaf import covers the branch.+ // Failures propagate intentionally: swallowing would leave a namespace in Iceberg+ // that Gravitino doesn't know about.+ importSchema(catalogName, leaf);++ // getMissingAncestors() only returns the not-yet-existing ancestors; append the leaf so that+ // every newly-created namespace in this request gets an owner assigned.+ newlyOwned.add(leaf);+ IcebergOwnershipUtils.setSchemaOwners(metalake,- context.catalogName(),- createRequest.namespace(),+ catalogName,+ newlyOwned,context.userName(),GravitinoEnv.getInstance().ownerDispatcher());+ return createNamespaceResponse;+ }- return response;+ /**+ * Returns all ancestor namespaces of {@code namespace} that do not currently exist in the+ * catalog. Uses {@link HierarchicalSchemaUtil#getAncestorNames} (the same utility as the+ * Gravitino REST API side) so the prefix-enumeration algorithm is shared.+ *+ * <p>For example, if {@code namespace} is {@code Namespace.of("A","B","C")} and only {@code+ * Namespace.of("A")} already exists, this returns {@code [Namespace.of("A","B")]}.+ */+ private List<Namespace> getMissingAncestors(IcebergRequestContext context, Namespace namespace) {+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ String namespaceName = String.join(separator, namespace.levels());+ List<String> ancestorNames = HierarchicalSchemaUtil.getAncestorNames(namespaceName, separator);+ // Iterate from innermost ancestor outward: in the hierarchical schema model the existence+ // of an inner ancestor implies the existence of all its outer ancestors, so we can stop+ // probing once we hit one that exists.+ List<Namespace> missing = new ArrayList<>();+ for (int i = ancestorNames.size() - 1; i >= 0; i--) {+ Namespace ancestor = Namespace.of(ancestorNames.get(i).split(Pattern.quote(separator)));+ if (dispatcher.namespaceExists(context, ancestor)) {+ break;+ }+ missing.add(ancestor);+ }+ // Reverse so the result is outermost-to-innermost (the order callers consume).+ Collections.reverse(missing);+ return missing;}@Override@@ -85,23 +139,53 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation@Overridepublic void dropNamespace(IcebergRequestContext context, Namespace namespace) {- dispatcher.dropNamespace(context, namespace);-- // Clean up the schema from Gravitino's entity store after successful drop- EntityStore store = GravitinoEnv.getInstance().entityStore();- try {- if (store != null) {- // Delete the entity for the dropped namespace (schema).- store.delete(- IcebergIdentifierUtils.toGravitinoSchemaIdentifier(- metalake, context.catalogName(), namespace),- Entity.EntityType.SCHEMA);- }- } catch (NoSuchEntityException ignore) {- // Ignore if the schema entity does not exist.- } catch (IOException ioe) {- throw new RuntimeException("io exception when deleting schema entity", ioe);- }+ String catalogName = context.catalogName();+ // Same top-level branch lock as createNamespace, so the phantom-row cleanup stays atomic+ // against concurrent creates that could re-add children under our ancestors.+ TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(metalake, catalogName, namespace.level(0)),+ LockType.WRITE,+ () -> {+ dispatcher.dropNamespace(context, namespace);++ // TODO: Use cascade mode deletion+ // Current behavior: only the leaf namespace is dropped from the Iceberg catalog above.+ // We walk ancestors outermost-to-leaf and clean up a Gravitino entity only while the+ // corresponding Iceberg namespace no longer exists, stopping at the first ancestor that+ // still exists. As a result, ancestor entities are cleaned up only when the underlying+ // Iceberg catalog also removes the empty parent namespaces on leaf-drop, which is+ // catalog-implementation-dependent. For catalogs that keep empty parents, operators may+ // need to drop empty parent namespaces manually.+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ List<Namespace> deleteTargets = Lists.newArrayList(namespace);+ String namespaceName = String.join(separator, namespace.levels());+ List<String> ancestorNames =+ HierarchicalSchemaUtil.getAncestorNames(namespaceName, separator);+ for (int i = ancestorNames.size() - 1; i >= 0; i--) {+ Namespace ancestor = Namespace.of(ancestorNames.get(i).split(Pattern.quote(separator)));+ if (dispatcher.namespaceExists(context, ancestor)) {+ break;+ }+ deleteTargets.add(ancestor);+ }++ EntityStore store = GravitinoEnv.getInstance().entityStore();+ if (store != null) {+ for (Namespace target : deleteTargets) {+ try {+ store.delete(+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ metalake, catalogName, target, separator),+ Entity.EntityType.SCHEMA);+ } catch (NoSuchEntityException ignore) {+ // Already gone.+ } catch (IOException ioe) {+ throw new RuntimeException("io exception when deleting schema entity", ioe);+ }+ }+ }+ return null;+ });}@Override@@ -148,7 +232,10 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationif (tableDispatcher != null) {tableDispatcher.loadTable(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, catalogName, TableIdentifier.of(namespace, tableName)));+ metalake,+ catalogName,+ TableIdentifier.of(namespace, tableName),+ HierarchicalSchemaUtil.schemaSeparator()));}}@@ -156,7 +243,8 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationSchemaDispatcher schemaDispatcher = GravitinoEnv.getInstance().schemaDispatcher();if (schemaDispatcher != null) {schemaDispatcher.loadSchema(- IcebergIdentifierUtils.toGravitinoSchemaIdentifier(metalake, catalogName, namespace));+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ metalake, catalogName, namespace, HierarchicalSchemaUtil.schemaSeparator()));}}}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnershipUtils.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnershipUtils.javaindex 1d30592593..f712881c5c 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnershipUtils.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnershipUtils.java@@ -18,10 +18,15 @@*/package org.apache.gravitino.iceberg.service.dispatcher;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;import org.apache.gravitino.Entity;+import org.apache.gravitino.MetadataObject;import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;@@ -53,13 +58,46 @@ public class IcebergOwnershipUtils {ownerDispatcher.setOwner(metalake,NameIdentifierUtil.toMetadataObject(- IcebergIdentifierUtils.toGravitinoSchemaIdentifier(metalake, catalogName, namespace),+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ metalake, catalogName, namespace, HierarchicalSchemaUtil.schemaSeparator()),Entity.EntityType.SCHEMA),user,Owner.Type.USER);}}+ /**+ * Sets the owner of multiple schemas (namespaces) to the specified user in a single dispatcher+ * call, when supported by the dispatcher. No-op when {@code ownerDispatcher} is {@code null} or+ * {@code namespaces} is empty.+ *+ * @param metalake the metalake name+ * @param catalogName the catalog name+ * @param namespaces the Iceberg namespaces to assign ownership for+ * @param user the user to set as owner+ * @param ownerDispatcher the owner dispatcher to use+ */+ public static void setSchemaOwners(+ String metalake,+ String catalogName,+ Collection<Namespace> namespaces,+ String user,+ OwnerDispatcher ownerDispatcher) {+ if (ownerDispatcher == null || namespaces.isEmpty()) {+ return;+ }+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ List<MetadataObject> objects = new ArrayList<>(namespaces.size());+ for (Namespace namespace : namespaces) {+ objects.add(+ NameIdentifierUtil.toMetadataObject(+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ metalake, catalogName, namespace, separator),+ Entity.EntityType.SCHEMA));+ }+ ownerDispatcher.setOwners(metalake, objects, user, Owner.Type.USER);+ }+/*** Sets the owner of a table to the specified user using the provided owner dispatcher.*@@ -82,7 +120,10 @@ public class IcebergOwnershipUtils {metalake,NameIdentifierUtil.toMetadataObject(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, catalogName, TableIdentifier.of(namespace, tableName)),+ metalake,+ catalogName,+ TableIdentifier.of(namespace, tableName),+ HierarchicalSchemaUtil.schemaSeparator()),Entity.EntityType.TABLE),user,Owner.Type.USER);@@ -111,7 +152,10 @@ public class IcebergOwnershipUtils {metalake,NameIdentifierUtil.toMetadataObject(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, catalogName, TableIdentifier.of(namespace, viewName)),+ metalake,+ catalogName,+ TableIdentifier.of(namespace, viewName),+ HierarchicalSchemaUtil.schemaSeparator()),Entity.EntityType.VIEW),user,Owner.Type.USER);diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.javaindex ed5d415627..1bd75e9b59 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java@@ -32,6 +32,7 @@ import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerConteimport org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.UpdateRequirement;import org.apache.iceberg.catalog.Namespace;@@ -97,7 +98,10 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatch// Delete the entity for the dropped table.store.delete(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), tableIdentifier),+ metalake,+ context.catalogName(),+ tableIdentifier,+ HierarchicalSchemaUtil.schemaSeparator()),Entity.EntityType.TABLE);}} catch (NoSuchEntityException ignore) {@@ -126,12 +130,13 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatch@Overridepublic void renameTable(IcebergRequestContext context, RenameTableRequest renameTableRequest) {dispatcher.renameTable(context, renameTableRequest);+ String separator = HierarchicalSchemaUtil.schemaSeparator();NameIdentifier tableSource =IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), renameTableRequest.source());+ metalake, context.catalogName(), renameTableRequest.source(), separator);NameIdentifier tableDest =IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), renameTableRequest.destination());+ metalake, context.catalogName(), renameTableRequest.destination(), separator);EntityStore store = GravitinoEnv.getInstance().entityStore();try {if (store != null) {@@ -204,9 +209,11 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatchif (tableDispatcher != null) {tableDispatcher.loadTable(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), TableIdentifier.of(namespace, tableName)));+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, tableName),+ HierarchicalSchemaUtil.schemaSeparator()));}-IcebergOwnershipUtils.setTableOwner(metalake,context.catalogName(),diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationExecutor.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationExecutor.javaindex f689ec9ef2..e32f2999f7 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationExecutor.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationExecutor.java@@ -33,6 +33,7 @@ import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerConteimport org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.rest.requests.CreateTableRequest;@@ -166,9 +167,10 @@ public class IcebergTableOperationExecutor implements IcebergTableOperationDispaprivate static CredentialPrivilege getCredentialPrivilege(IcebergRequestContext context, TableIdentifier tableIdentifier) {String metalake = IcebergRESTServerContext.getInstance().metalakeName();+ String separator = HierarchicalSchemaUtil.schemaSeparator();NameIdentifier identifier =IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), tableIdentifier);+ metalake, context.catalogName(), tableIdentifier, separator);boolean writable =MetadataAuthzHelper.checkAccess(identifier,diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.javaindex e737c81a4e..22d22724cd 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java@@ -28,6 +28,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.rest.requests.CreateViewRequest;@@ -103,7 +104,10 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcherif (store != null) {store.delete(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), viewIdentifier),+ metalake,+ context.catalogName(),+ viewIdentifier,+ HierarchicalSchemaUtil.schemaSeparator()),Entity.EntityType.VIEW);LOG.info("Successfully removed view from Gravitino entity store: {}.{}.{}.{}",@@ -147,12 +151,13 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcherdispatcher.renameView(context, renameViewRequest);// Update view in Gravitino entity store with new name+ String separator = HierarchicalSchemaUtil.schemaSeparator();NameIdentifier sourceIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), renameViewRequest.source());+ metalake, context.catalogName(), renameViewRequest.source(), separator);NameIdentifier destIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, context.catalogName(), renameViewRequest.destination());+ metalake, context.catalogName(), renameViewRequest.destination(), separator);EntityStore store = GravitinoEnv.getInstance().entityStore();try {@@ -208,7 +213,10 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatchertry {viewDispatcher.loadView(IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake, catalogName, TableIdentifier.of(namespace, viewName)));+ metalake,+ catalogName,+ TableIdentifier.of(namespace, viewName),+ HierarchicalSchemaUtil.schemaSeparator()));LOG.info("Successfully imported view into Gravitino: {}.{}.{}.{}",metalake,diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.javaindex ddc5c100ff..3f486859dc 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java@@ -25,6 +25,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.google.common.annotations.VisibleForTesting;import java.util.ArrayList;import java.util.List;+import java.util.regex.Pattern;import javax.inject.Inject;import javax.servlet.http.HttpServletRequest;import javax.ws.rs.Consumes;@@ -55,8 +56,10 @@ import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;+import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.gravitino.server.web.Utils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.rest.RESTUtil;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;@@ -225,11 +228,13 @@ public class IcebergNamespaceOperations {@Timed(name = "create-namespace." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "create-namespace", absolute = true)@AuthorizationExpression(- expression = "ANY(OWNER, METALAKE, CATALOG) || ANY_USE_CATALOG && ANY_CREATE_SCHEMA",- accessMetadataType = MetadataObject.Type.CATALOG)+ expression = "ANY(OWNER, METALAKE, CATALOG, SCHEMA) || ANY_USE_CATALOG && ANY_CREATE_SCHEMA",+ accessMetadataType = MetadataObject.Type.SCHEMA)public Response createNamespace(@AuthorizationMetadata(type = Entity.EntityType.CATALOG) @PathParam("prefix") String prefix,- CreateNamespaceRequest createNamespaceRequest) {+ @IcebergAuthorizationMetadata(+ type = IcebergAuthorizationMetadata.RequestType.CREATE_NAMESPACE)+ CreateNamespaceRequest createNamespaceRequest) {String catalogName = IcebergRESTUtils.getCatalogName(prefix);LOG.info("Create Iceberg namespace, catalog: {}, createNamespaceRequest: {}",@@ -332,13 +337,14 @@ public class IcebergNamespaceOperations {private NameIdentifier[] toNameIdentifiers(ListNamespacesResponse listNamespacesResponse, String metalake, String catalogName) {+ String separator = HierarchicalSchemaUtil.schemaSeparator();List<Namespace> namespaces = listNamespacesResponse.namespaces();NameIdentifier[] nameIdentifiers = new NameIdentifier[namespaces.size()];for (int i = 0; i < namespaces.size(); i++) {Namespace namespace = namespaces.get(i);- // Convert Iceberg Namespace to Gravitino NameIdentifier- // Namespace should have at least one level for schema name- String schemaName = namespace.isEmpty() ? "" : namespace.level(0);+ // Join namespace levels with the logical separator to form the Gravitino schema name,+ // e.g. Namespace.of("A","B","C") -> "A:B:C" -> NameIdentifier(metalake, catalog, "A:B:C").+ String schemaName = namespace.isEmpty() ? "" : String.join(separator, namespace.levels());nameIdentifiers[i] = NameIdentifier.of(metalake, catalogName, schemaName);}return nameIdentifiers;@@ -346,6 +352,7 @@ public class IcebergNamespaceOperations {private ListNamespacesResponse filterListNamespacesResponse(ListNamespacesResponse listNamespacesResponse, String metalake, String catalogName) {+ String separator = HierarchicalSchemaUtil.schemaSeparator();NameIdentifier[] idents =MetadataAuthzHelper.filterByExpression(metalake,@@ -354,11 +361,9 @@ public class IcebergNamespaceOperations {toNameIdentifiers(listNamespacesResponse, metalake, catalogName));List<Namespace> filteredNamespaces = new ArrayList<>();for (NameIdentifier ident : idents) {- // Convert back from NameIdentifier to Iceberg Namespaceif (ident.hasNamespace() && ident.namespace().levels().length >= 2) {- // Schema name is the last level in the namespace- String schemaName = ident.name();- filteredNamespaces.add(Namespace.of(schemaName));+ // Convert the logical schema name (e.g. "A:B:C") back to a multi-level Iceberg Namespace.+ filteredNamespaces.add(Namespace.of(ident.name().split(Pattern.quote(separator), -1)));}}return ListNamespacesResponse.builder().addAll(filteredNamespaces).build();diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.javaindex 98c73e2da6..d537de2b8e 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java@@ -52,6 +52,7 @@ import org.apache.gravitino.Entity;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;import org.apache.gravitino.iceberg.service.IcebergObjectMapper;import org.apache.gravitino.iceberg.service.IcebergRESTUtils;@@ -67,6 +68,7 @@ import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizatioimport org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata.RequestType;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.gravitino.server.web.Utils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.SnapshotRef;import org.apache.iceberg.TableMetadata;import org.apache.iceberg.catalog.Namespace;@@ -637,7 +639,11 @@ public class IcebergTableOperations {TableIdentifier identifier = identifiers.get(i);nameIdentifiers[i] =NameIdentifier.of(- metalake, catalogName, identifier.namespace().level(0), identifier.name());+ metalake,+ catalogName,+ IcebergIdentifierUtils.icebergNamespaceToSchemaName(+ identifier.namespace(), HierarchicalSchemaUtil.schemaSeparator()),+ identifier.name());}return nameIdentifiers;}@@ -653,7 +659,10 @@ public class IcebergTableOperations {List<TableIdentifier> filteredIdentifiers = new ArrayList<>();for (NameIdentifier ident : idents) {filteredIdentifiers.add(- TableIdentifier.of(Namespace.of(ident.namespace().level(2)), ident.name()));+ TableIdentifier.of(+ IcebergIdentifierUtils.getIcebergNamespaceFromSchemaName(+ ident.namespace().level(2), HierarchicalSchemaUtil.schemaSeparator()),+ ident.name()));}return ListTablesResponse.builder().addAll(filteredIdentifiers)diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.javaindex c94ef3a340..2a456277dc 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java@@ -43,6 +43,7 @@ import org.apache.gravitino.Entity;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;import org.apache.gravitino.iceberg.service.IcebergObjectMapper;import org.apache.gravitino.iceberg.service.IcebergRESTUtils;@@ -55,6 +56,7 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationExpresimport org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.gravitino.server.web.Utils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.rest.RESTUtil;@@ -337,7 +339,11 @@ public class IcebergViewOperations {TableIdentifier identifier = identifiers.get(i);nameIdentifiers[i] =NameIdentifier.of(- metalake, catalogName, identifier.namespace().level(0), identifier.name());+ metalake,+ catalogName,+ IcebergIdentifierUtils.icebergNamespaceToSchemaName(+ identifier.namespace(), HierarchicalSchemaUtil.schemaSeparator()),+ identifier.name());}return nameIdentifiers;}@@ -353,7 +359,10 @@ public class IcebergViewOperations {List<TableIdentifier> filteredIdentifiers = new ArrayList<>();for (NameIdentifier ident : idents) {filteredIdentifiers.add(- TableIdentifier.of(Namespace.of(ident.namespace().level(2)), ident.name()));+ TableIdentifier.of(+ IcebergIdentifierUtils.getIcebergNamespaceFromSchemaName(+ ident.namespace().level(2), HierarchicalSchemaUtil.schemaSeparator()),+ ident.name()));}return ListTablesResponse.builder().addAll(filteredIdentifiers)diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.javaindex 255a0aa312..9ba92fab56 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java@@ -32,6 +32,7 @@ public @interface IcebergAuthorizationMetadata {LOAD_TABLE,RENAME_TABLE,RENAME_VIEW,+ CREATE_NAMESPACE,}/*** The type of the parameter to be used for authorization.diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.javanew file mode 100644index 0000000000..52bf8429e5--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java@@ -0,0 +1,95 @@+/*+ * 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.server.web.filter;++import java.lang.reflect.Parameter;+import java.util.Arrays;+import java.util.Map;+import org.apache.gravitino.Entity.EntityType;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;+import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;+import org.apache.gravitino.utils.NameIdentifierUtil;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.exceptions.ForbiddenException;+import org.apache.iceberg.rest.requests.CreateNamespaceRequest;++/**+ * Handler for CREATE_NAMESPACE operations. For nested namespace creation (e.g. {@code A:B:C}),+ * injects the parent schema ({@code A:B}) into the authorization context so that the standard+ * expression can check {@code CREATE_SCHEMA} against the already-existing parent.+ *+ * <p>For top-level namespaces no SCHEMA is injected and the standard expression falls back to+ * CATALOG-level checks. Authorization is completed by the standard expression evaluator ({@link+ * #authorizationCompleted()} returns {@code false}).+ */+public class CreateNamespaceAuthzHandler implements AuthorizationHandler {+ private final Parameter[] parameters;+ private final Object[] args;++ public CreateNamespaceAuthzHandler(Parameter[] parameters, Object[] args) {+ this.parameters = parameters;+ this.args = args;+ }++ @Override+ public void process(Map<EntityType, NameIdentifier> nameIdentifierMap) {+ CreateNamespaceRequest request = extractRequest();++ NameIdentifier catalogIdent = nameIdentifierMap.get(EntityType.CATALOG);+ if (catalogIdent == null) {+ throw new ForbiddenException("Missing catalog context for namespace creation authorization");+ }+ String metalake = catalogIdent.namespace().level(0);+ String catalog = catalogIdent.name();++ Namespace namespace = request.namespace();+ int levels = namespace.length();++ String separator = HierarchicalSchemaUtil.schemaSeparator();++ // For nested namespaces inject the parent schema so the expression evaluates against it.+ // JcasbinAuthorizer inheritance then walks A:B → A → CATALOG automatically.+ // For top-level namespaces no SCHEMA is injected; the expression uses CATALOG-level checks.+ if (levels > 1) {+ String parentPath = String.join(separator, Arrays.copyOf(namespace.levels(), levels - 1));+ nameIdentifierMap.put(+ EntityType.SCHEMA, NameIdentifierUtil.ofSchema(metalake, catalog, parentPath));+ }+ }++ @Override+ public boolean authorizationCompleted() {+ return false;+ }++ private CreateNamespaceRequest extractRequest() {+ for (int i = 0; i < parameters.length; i++) {+ IcebergAuthorizationMetadata metadata =+ parameters[i].getAnnotation(IcebergAuthorizationMetadata.class);+ if (metadata != null+ && metadata.type() == IcebergAuthorizationMetadata.RequestType.CREATE_NAMESPACE) {+ return (CreateNamespaceRequest) args[i];+ }+ }+ throw new ForbiddenException("CreateNamespaceRequest not found in method parameters");+ }+}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.javaindex 0ff52f2781..0612a31005 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.java@@ -33,6 +33,7 @@ import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerConteimport org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata.RequestType;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.rest.RESTUtil;@@ -50,52 +51,53 @@ public class IcebergMetadataAuthorizationMethodInterceptorParameter[] parameters, Object[] args) {Map<Entity.EntityType, NameIdentifier> nameIdentifierMap = new HashMap<>();nameIdentifierMap.put(Entity.EntityType.METALAKE, NameIdentifierUtil.ofMetalake(metalakeName));- // get catalog & namespace from paramsString catalog = null;String schema = null;Namespace rawNamespace = null;+ String separator = HierarchicalSchemaUtil.schemaSeparator();for (int i = 0; i < parameters.length; i++) {Parameter parameter = parameters[i];AuthorizationMetadata authorizeResource =parameter.getAnnotation(AuthorizationMetadata.class);- if (authorizeResource == null) {+ if (authorizeResource != null) {+ Entity.EntityType type = authorizeResource.type();+ String value = String.valueOf(args[i]);+ switch (type) {+ case CATALOG:+ catalog = IcebergRESTUtils.getCatalogName(value);+ nameIdentifierMap.put(+ Entity.EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalakeName, catalog));+ break;+ case SCHEMA:+ rawNamespace = RESTUtil.decodeNamespace(value);+ schema = String.join(separator, rawNamespace.levels());+ nameIdentifierMap.put(+ Entity.EntityType.SCHEMA,+ NameIdentifierUtil.ofSchema(metalakeName, catalog, schema));+ break;+ case TABLE:+ nameIdentifierMap.put(+ EntityType.TABLE,+ NameIdentifierUtil.ofTable(+ metalakeName, catalog, schema, RESTUtil.decodeString(value)));+ break;+ case VIEW:+ String decodedViewName = RESTUtil.decodeString(value);+ nameIdentifierMap.put(+ EntityType.VIEW,+ NameIdentifierUtil.ofView(metalakeName, catalog, schema, decodedViewName));+ // Also register as TABLE so ANY_SELECT_TABLE in+ // ICEBERG_LOAD_VIEW_AUTHORIZATION_EXPRESSION+ // matches when Spark probes viewExists(tableName) during table resolution.+ nameIdentifierMap.put(+ EntityType.TABLE,+ NameIdentifierUtil.ofTable(metalakeName, catalog, schema, decodedViewName));+ break;+ default:+ break;+ }continue;}- Entity.EntityType type = authorizeResource.type();- String value = String.valueOf(args[i]);- switch (type) {- case CATALOG:- catalog = IcebergRESTUtils.getCatalogName(value);- nameIdentifierMap.put(- Entity.EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalakeName, catalog));- break;- case SCHEMA:- rawNamespace = RESTUtil.decodeNamespace(value);- schema = rawNamespace.level(rawNamespace.length() - 1);- nameIdentifierMap.put(- Entity.EntityType.SCHEMA, NameIdentifierUtil.ofSchema(metalakeName, catalog, schema));- break;- case TABLE:- nameIdentifierMap.put(- EntityType.TABLE,- NameIdentifierUtil.ofTable(- metalakeName, catalog, schema, RESTUtil.decodeString(value)));- break;- case VIEW:- String decodedViewName = RESTUtil.decodeString(value);- nameIdentifierMap.put(- EntityType.VIEW,- NameIdentifierUtil.ofView(metalakeName, catalog, schema, decodedViewName));- // Also register as TABLE so ANY_SELECT_TABLE in- // ICEBERG_LOAD_VIEW_AUTHORIZATION_EXPRESSION- // matches when Spark probes viewExists(tableName) during table resolution.- nameIdentifierMap.put(- EntityType.TABLE,- NameIdentifierUtil.ofTable(metalakeName, catalog, schema, decodedViewName));- break;- default:- break;- }}return nameIdentifierMap;}@@ -120,6 +122,8 @@ public class IcebergMetadataAuthorizationMethodInterceptorreturn Optional.of(new RenameTableAuthzHandler(parameters, args));case RENAME_VIEW:return Optional.of(new RenameViewAuthzHandler(parameters, args));+ case CREATE_NAMESPACE:+ return Optional.of(new CreateNamespaceAuthzHandler(parameters, args));default:break;}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.javaindex f839858b57..4df2f41068 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java@@ -29,6 +29,7 @@ import org.apache.gravitino.authorization.AuthorizationRequestContext;import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.exceptions.ForbiddenException;@@ -80,7 +81,8 @@ public class RenameTableAuthzHandler implements AuthorizationHandler {// Extract source table information from the request and add to map// The source table is NOT extracted via standard @AuthorizationMetadata annotations// because it's embedded in the RenameTableRequest body- String sourceSchema = renameTableRequest.source().namespace().level(0);+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ String sourceSchema = String.join(separator, renameTableRequest.source().namespace().levels());String sourceTable = renameTableRequest.source().name();nameIdentifierMap.put(@@ -89,7 +91,8 @@ public class RenameTableAuthzHandler implements AuthorizationHandler {EntityType.TABLE,NameIdentifierUtil.ofTable(metalakeName, catalog, sourceSchema, sourceTable));- String destSchema = renameTableRequest.destination().namespace().level(0);+ String destSchema =+ String.join(separator, renameTableRequest.destination().namespace().levels());if (!sourceSchema.equals(destSchema)) {// Cross-namespace rename - perform complete authorization herecrossNamespaceRename = true;diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.javaindex 268627b2ef..08630981bd 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java@@ -29,6 +29,7 @@ import org.apache.gravitino.authorization.AuthorizationRequestContext;import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.exceptions.ForbiddenException;@@ -80,7 +81,8 @@ public class RenameViewAuthzHandler implements AuthorizationHandler {// Extract source view information from the request and add to map// The source view is NOT extracted via standard @AuthorizationMetadata annotations// because it's embedded in the RenameTableRequest body- String sourceSchema = renameViewRequest.source().namespace().level(0);+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ String sourceSchema = String.join(separator, renameViewRequest.source().namespace().levels());String sourceView = renameViewRequest.source().name();nameIdentifierMap.put(@@ -89,7 +91,8 @@ public class RenameViewAuthzHandler implements AuthorizationHandler {EntityType.VIEW,NameIdentifierUtil.ofView(metalakeName, catalog, sourceSchema, sourceView));- String destSchema = renameViewRequest.destination().namespace().level(0);+ String destSchema =+ String.join(separator, renameViewRequest.destination().namespace().levels());if (!sourceSchema.equals(destSchema)) {// Cross-namespace rename - perform complete authorization herecrossNamespaceRename = true;diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergAuthorizationIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergAuthorizationIT.javaindex 63fcc10a59..e16da44ff0 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergAuthorizationIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergAuthorizationIT.java@@ -47,7 +47,12 @@ import org.apache.gravitino.integration.test.util.TestDatabaseName;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.server.authorization.jcasbin.JcasbinAuthorizer;+import org.apache.hadoop.conf.Configuration;import org.apache.iceberg.CatalogProperties;+import org.apache.iceberg.Schema;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.rest.RESTCatalog;import org.apache.spark.SparkConf;import org.apache.spark.sql.Row;import org.apache.spark.sql.SparkSession;@@ -80,6 +85,10 @@ public class IcebergAuthorizationIT extends BaseIT {private static ContainerSuite containerSuite = ContainerSuite.getInstance();private SparkSession sparkSession;+ // IRC REST catalog authenticated as SUPER_USER, used for setup operations that the Gravitino+ // REST API cannot perform — e.g. creating hierarchical schemas whose names contain the+ // configured schema separator (Gravitino rejects those names at the REST boundary).+ protected RESTCatalog adminIcebergCatalog;@BeforeAll@Override@@ -88,11 +97,19 @@ public class IcebergAuthorizationIT extends BaseIT {startGravitinoServerWithIcebergREST();initMetalakeAndCatalog();initSparkEnv();+ initAdminIcebergCatalog();}@AfterAll@Overridepublic void stopIntegrationTest() throws IOException, InterruptedException {+ if (adminIcebergCatalog != null) {+ try {+ adminIcebergCatalog.close();+ } catch (Exception e) {+ LOG.warn("Failed to close admin Iceberg REST catalog", e);+ }+ }sparkSession.close();client.dropMetalake(METALAKE_NAME, true);@@ -228,6 +245,45 @@ public class IcebergAuthorizationIT extends BaseIT {Assertions.assertTrue(exists);}+ /**+ * Initialize a REST catalog client authenticated as {@link #SUPER_USER}. Tests use it to perform+ * admin setup operations such as creating hierarchical schemas.+ */+ private void initAdminIcebergCatalog() {+ Map<String, String> props = Maps.newHashMap();+ props.put(CatalogProperties.URI, getIcebergRestServiceUri());+ props.put(CatalogProperties.CACHE_ENABLED, "false");+ props.put("rest.auth.type", "basic");+ props.put("rest.auth.basic.username", SUPER_USER);+ props.put("rest.auth.basic.password", "mock");+ RESTCatalog catalog = new RESTCatalog();+ catalog.setConf(new Configuration());+ catalog.initialize("admin", props);+ adminIcebergCatalog = catalog;+ }++ /**+ * Creates a nested Iceberg namespace via the IRC API as {@link #SUPER_USER}. The hook dispatcher+ * auto-creates any missing parent namespaces and imports every newly-created namespace into+ * Gravitino as a schema entity, so the test only needs to issue a single call for the deepest+ * level.+ */+ protected void createNestedNamespaceViaIRC(String... levels) {+ adminIcebergCatalog.createNamespace(Namespace.of(levels));+ }++ /** Creates a 2-column Iceberg table via the IRC API as {@link #SUPER_USER}. */+ protected void createTableViaIRC(String[] namespaceLevels, String tableName) {+ Schema schema =+ new Schema(+ org.apache.iceberg.types.Types.NestedField.required(+ 1, "col_1", org.apache.iceberg.types.Types.IntegerType.get(), "col_1_comment"),+ org.apache.iceberg.types.Types.NestedField.required(+ 2, "col_2", org.apache.iceberg.types.Types.IntegerType.get(), "col_2_comment"));+ adminIcebergCatalog.createTable(+ TableIdentifier.of(Namespace.of(namespaceLevels), tableName), schema);+ }+private void initSparkEnv() {String icebergRESTUri = getIcebergRestServiceUri();LOG.info("Iceberg REST uri: {}", icebergRESTUri);diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergNamespaceAuthorizationIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergNamespaceAuthorizationIT.javaindex b8106b09e6..e1968bcab4 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergNamespaceAuthorizationIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergNamespaceAuthorizationIT.java@@ -32,6 +32,7 @@ import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.Privileges;import org.apache.gravitino.authorization.SecurableObject;import org.apache.gravitino.authorization.SecurableObjects;+import org.apache.iceberg.exceptions.ForbiddenException;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;@@ -103,8 +104,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Should fail without proper authorizationAssertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,- () -> sql("CREATE DATABASE %s", namespace));+ ForbiddenException.class, () -> sql("CREATE DATABASE %s", namespace));// Grant CREATE_SCHEMA and USE_CATALOG privileges and verify creation succeedsgrantUseCatalogRole(GRAVITINO_CATALOG_NAME);@@ -122,6 +122,26 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {Assertions.assertEquals(NORMAL_USER, schemaOwner.get().name());}+ @Test+ void testCreateSchemaPrivilegeOnChildDoesNotAllowUnrelatedTopLevel() {+ String parentNamespace = "ns_child_priv_parent";+ String childNamespaceInGravitino = parentNamespace + ":child";+ String unrelatedTopLevel = "ns_child_priv_unrelated";++ // Create the parent/child branch as admin so the child schema exists to grant on.+ createNestedNamespaceViaIRC(parentNamespace, "child");++ // Grant USE_CATALOG plus CREATE_SCHEMA scoped only to the child schema (A:B).+ grantUseCatalogRole(GRAVITINO_CATALOG_NAME);+ grantCreateSchemaOnSchemaRole(childNamespaceInGravitino);++ // CREATE_SCHEMA on a child schema must not allow creating an unrelated top-level schema: the+ // top-level path injects no SCHEMA context, so the expression falls back to catalog-level+ // checks, which the normal user does not satisfy.+ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("CREATE DATABASE %s", unrelatedTopLevel));+ }+@Testvoid testListNamespaces() {String namespace1 = "ns_list_hidden1";@@ -145,8 +165,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Without any roles, even SHOW DATABASES should failrevokeUserRoles();resetMetalakeAndCatalogOwner();- Assertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class, () -> sql("SHOW DATABASES"));+ Assertions.assertThrowsExactly(ForbiddenException.class, () -> sql("SHOW DATABASES"));}@Test@@ -185,8 +204,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {.createSchema(namespace, "test schema", new HashMap<>());// Access should fail without proper privileges- Assertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class, () -> sql("USE %s", namespace));+ Assertions.assertThrowsExactly(ForbiddenException.class, () -> sql("USE %s", namespace));// Grant schema access and verify successgrantUseCatalogRole(GRAVITINO_CATALOG_NAME);@@ -194,6 +212,95 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {Assertions.assertDoesNotThrow(() -> sql("USE %s", namespace));}+ @Test+ void testUseNestedNamespace() {+ String parentNamespace = "ns_nested_parent";+ String nestedNamespaceInGravitino = parentNamespace + ":child";+ String nestedNamespaceInIceberg = parentNamespace + ".child";++ createNestedNamespaceViaIRC(parentNamespace, "child");++ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("USE %s", nestedNamespaceInIceberg));++ grantUseCatalogRole(GRAVITINO_CATALOG_NAME);+ grantUseSchemaRole(nestedNamespaceInGravitino);+ Assertions.assertDoesNotThrow(() -> sql("USE %s", nestedNamespaceInIceberg));+ }++ @Test+ void testUseNestedNamespaceWithInheritedParentPrivilege() {+ String parentNamespace = "ns_nested_inherit_parent";+ String nestedNamespaceInIceberg = parentNamespace + ".child";++ createNestedNamespaceViaIRC(parentNamespace, "child");++ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("USE %s", nestedNamespaceInIceberg));++ grantUseCatalogRole(GRAVITINO_CATALOG_NAME);+ grantUseSchemaRole(parentNamespace);+ Assertions.assertDoesNotThrow(+ () -> sql("USE %s", nestedNamespaceInIceberg),+ "USE_SCHEMA on parent namespace should be inherited by child namespace");+ }++ @Test+ void testUpdateNestedNamespace() {+ String parentNamespace = "ns_nested_update_parent";+ String nestedNamespaceInGravitino = parentNamespace + ":child";+ String nestedNamespaceInIceberg = parentNamespace + ".child";++ createNestedNamespaceViaIRC(parentNamespace, "child");+ grantUseCatalogRole(GRAVITINO_CATALOG_NAME);++ Assertions.assertThrowsExactly(+ ForbiddenException.class,+ () ->+ sql(+ "ALTER DATABASE %s SET DBPROPERTIES ('nestedKey'='nestedValue')",+ nestedNamespaceInIceberg));++ metalakeClientWithAllPrivilege.setOwner(+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedNamespaceInGravitino),+ MetadataObject.Type.SCHEMA),+ NORMAL_USER,+ Owner.Type.USER);+ grantUseSchemaRole(nestedNamespaceInGravitino);+ Assertions.assertDoesNotThrow(+ () ->+ sql(+ "ALTER DATABASE %s SET DBPROPERTIES ('nestedKey'='nestedValue')",+ nestedNamespaceInIceberg));+ }++ @Test+ void testDropNestedNamespace() {+ String parentNamespace = "ns_nested_drop_parent";+ String nestedNamespaceInGravitino = parentNamespace + ":child";+ String nestedNamespaceInIceberg = parentNamespace + ".child";++ createNestedNamespaceViaIRC(parentNamespace, "child");+ grantUseCatalogRole(GRAVITINO_CATALOG_NAME);++ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("DROP DATABASE %s", nestedNamespaceInIceberg));++ metalakeClientWithAllPrivilege.setOwner(+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedNamespaceInGravitino),+ MetadataObject.Type.SCHEMA),+ NORMAL_USER,+ Owner.Type.USER);+ grantUseSchemaRole(nestedNamespaceInGravitino);+ Assertions.assertDoesNotThrow(() -> sql("DROP DATABASE %s", nestedNamespaceInIceberg));++ boolean exists =+ catalogClientWithAllPrivilege.asSchemas().schemaExists(nestedNamespaceInGravitino);+ Assertions.assertFalse(exists, "Nested schema should be deleted");+ }+@Testvoid testUpdateNamespace() {String namespace = "ns_modification";@@ -205,7 +312,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Non-owners cannot modify schemas even with USE_CATALOG privilegeAssertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,+ ForbiddenException.class,() -> sql("ALTER DATABASE %s SET DBPROPERTIES ('key'='value')", namespace));// Schema ownership enables modification@@ -236,8 +343,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Non-owner cannot delete schemaAssertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,- () -> sql("DROP DATABASE %s", namespace));+ ForbiddenException.class, () -> sql("DROP DATABASE %s", namespace));// Transfer ownership to normal usermetalakeClientWithAllPrivilege.setOwner(@@ -265,8 +371,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {.createSchema(namespace, "test schema", new HashMap<>());// Schema access requires proper authorization- Assertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class, () -> sql("USE %s", namespace));+ Assertions.assertThrowsExactly(ForbiddenException.class, () -> sql("USE %s", namespace));grantUseCatalogRole(GRAVITINO_CATALOG_NAME);grantUseSchemaRole(namespace);@@ -317,7 +422,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Registration should fail without destination schema ownershipAssertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,+ ForbiddenException.class,() ->sql("CALL rest.system.register_table(table => '%s.%s', metadata_file=> '%s')",@@ -363,13 +468,13 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Verify operations fail without authorizationAssertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,+ ForbiddenException.class,() -> sql("ALTER DATABASE %s SET DBPROPERTIES ('key1'='value1')", namespace));// USE_CATALOG alone is insufficient for schema modificationgrantUseCatalogRole(GRAVITINO_CATALOG_NAME);Assertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,+ ForbiddenException.class,() -> sql("ALTER DATABASE %s SET DBPROPERTIES ('key2'='value2')", namespace));// Schema ownership with USE_CATALOG enables modification@@ -388,8 +493,7 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {// Authorization is checked before existence - security best practiceString nonExistentSchema = "non_existent_schema";Assertions.assertThrowsExactly(- org.apache.iceberg.exceptions.ForbiddenException.class,- () -> sql("USE %s", nonExistentSchema));+ ForbiddenException.class, () -> sql("USE %s", nonExistentSchema));// Special characters in schema names should work with authorizationString specialSchema = "schema_with_123_special";@@ -438,6 +542,20 @@ public class IcebergNamespaceAuthorizationIT extends IcebergAuthorizationIT {metalakeClientWithAllPrivilege.grantRolesToUser(ImmutableList.of(roleName), NORMAL_USER);}+ /** Grants CREATE_SCHEMA privilege to the normal user scoped to the specified schema. */+ private void grantCreateSchemaOnSchemaRole(String schemaName) {+ String roleName = "createSchemaOnSchema_" + UUID.randomUUID();+ SecurableObject catalogObject =+ SecurableObjects.ofCatalog(GRAVITINO_CATALOG_NAME, ImmutableList.of());+ SecurableObject schemaObject =+ SecurableObjects.ofSchema(+ catalogObject, schemaName, ImmutableList.of(Privileges.CreateSchema.allow()));++ metalakeClientWithAllPrivilege.createRole(+ roleName, new HashMap<>(), ImmutableList.of(schemaObject));+ metalakeClientWithAllPrivilege.grantRolesToUser(ImmutableList.of(roleName), NORMAL_USER);+ }+/** Extracts schema names from SHOW DATABASES result, handling various result formats. */private List<String> extractSchemaNames(List<Object[]> result) {List<String> schemaNames = new ArrayList<>();diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergTableAuthorizationIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergTableAuthorizationIT.javaindex fd3fb00ae1..cea3f1acce 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergTableAuthorizationIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergTableAuthorizationIT.java@@ -133,6 +133,130 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {Assertions.assertFalse(exists);}+ @Test+ void testCreateTableInNestedNamespace() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested";+ String tableName = "test_nested_create";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested");+ grantUseSchemaRole(nestedSchemaInGravitino);+ sql("USE %s;", nestedSchemaInIceberg);++ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("CREATE TABLE %s(a int)", tableName));++ String roleName = grantCreateTableRole(nestedSchemaInGravitino);+ Assertions.assertDoesNotThrow(() -> sql("CREATE TABLE %s(a int)", tableName));+ revokeRole(roleName);++ boolean exists =+ catalogClientWithAllPrivilege+ .asTableCatalog()+ .tableExists(NameIdentifier.of(nestedSchemaInGravitino, tableName));+ Assertions.assertTrue(exists);+ }++ @Test+ void testCreateTableInNestedNamespaceWithInheritedParentPrivilege() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested_inherit";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_inherit";+ String tableName = "test_nested_inherited_create";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_inherit");++ Assertions.assertThrowsExactly(+ ForbiddenException.class,+ () -> {+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE TABLE %s(a int)", tableName);+ });++ grantUseSchemaRole(SCHEMA_NAME);+ grantCreateTableRole(SCHEMA_NAME);+ Assertions.assertDoesNotThrow(+ () -> {+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE TABLE %s(a int)", tableName);+ },+ "Schema-level privileges on parent namespace should be inherited by child namespace");++ boolean exists =+ catalogClientWithAllPrivilege+ .asTableCatalog()+ .tableExists(NameIdentifier.of(nestedSchemaInGravitino, tableName));+ Assertions.assertTrue(exists);+ }++ @Test+ void testLoadUpdateDropTableInNestedNamespace() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested_crud";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_crud";+ String tableName = "test_nested_crud";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_crud");+ grantUseSchemaRole(nestedSchemaInGravitino);+ String createRole = grantCreateTableRole(nestedSchemaInGravitino);+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE TABLE %s(a int)", tableName);+ revokeRole(createRole);++ // The creator becomes table owner, so read should be allowed without explicit SELECT privilege.+ Assertions.assertDoesNotThrow(() -> sql("DESC TABLE %s", tableName));++ // Transfer ownership away to verify table-level SELECT privilege still works for nested+ // schemas.+ MetadataObject tableMetadataObject =+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedSchemaInGravitino, tableName),+ MetadataObject.Type.TABLE);+ metalakeClientWithAllPrivilege.setOwner(tableMetadataObject, SUPER_USER, Owner.Type.USER);+ Assertions.assertThrowsExactly(ForbiddenException.class, () -> sql("DESC TABLE %s", tableName));++ String selectRole = grantSelectTableRole(nestedSchemaInGravitino, tableName);+ Assertions.assertDoesNotThrow(() -> sql("DESC TABLE %s", tableName));+ revokeRole(selectRole);++ String modifyRole = grantModifyTableRole(nestedSchemaInGravitino, tableName);+ Assertions.assertDoesNotThrow(+ () -> sql("ALTER TABLE %s SET TBLPROPERTIES ('nested_key'='nested_value')", tableName));+ revokeRole(modifyRole);++ Table table =+ catalogClientWithAllPrivilege+ .asTableCatalog()+ .loadTable(NameIdentifier.of(nestedSchemaInGravitino, tableName));+ Assertions.assertEquals("nested_value", table.properties().get("nested_key"));++ setTableOwner(nestedSchemaInGravitino, tableName);+ Assertions.assertDoesNotThrow(() -> sql("DROP TABLE %s", tableName));++ boolean exists =+ catalogClientWithAllPrivilege+ .asTableCatalog()+ .tableExists(NameIdentifier.of(nestedSchemaInGravitino, tableName));+ Assertions.assertFalse(exists);+ }++ @Test+ void testListNestedNamespaceTablesWithInheritedParentPrivilege() {+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_list";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_list");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested_list"}, "nested_list_t1");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested_list"}, "nested_list_t2");++ Set<String> tableNames = listTableNames(nestedSchemaInIceberg);+ Assertions.assertEquals(0, tableNames.size());++ grantUseSchemaRole(SCHEMA_NAME);+ setSchemaOwner(SCHEMA_NAME, NORMAL_USER);+ tableNames = listTableNames(nestedSchemaInIceberg);+ Assertions.assertTrue(tableNames.contains("nested_list_t1"));+ Assertions.assertTrue(tableNames.contains("nested_list_t2"));+ setSchemaOwner(SCHEMA_NAME, SUPER_USER);+ }+@Testvoid testLoadTable() {String tableName = "test_load";@@ -589,6 +713,10 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {}private String grantSelectTableRole(String tableName) {+ return grantSelectTableRole(SCHEMA_NAME, tableName);+ }++ private String grantSelectTableRole(String schema, String tableName) {String roleName = "selectTable_" + UUID.randomUUID();List<SecurableObject> securableObjects = new ArrayList<>();SecurableObject catalogObject =@@ -597,7 +725,7 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {securableObjects.add(catalogObject);SecurableObject schemaObject =SecurableObjects.ofSchema(- catalogObject, SCHEMA_NAME, ImmutableList.of(Privileges.UseSchema.allow()));+ catalogObject, schema, ImmutableList.of(Privileges.UseSchema.allow()));securableObjects.add(schemaObject);SecurableObject tableObject =SecurableObjects.ofTable(@@ -609,6 +737,10 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {}private String grantModifyTableRole(String tableName) {+ return grantModifyTableRole(SCHEMA_NAME, tableName);+ }++ private String grantModifyTableRole(String schema, String tableName) {String roleName = "modifyTable_" + UUID.randomUUID();List<SecurableObject> securableObjects = new ArrayList<>();SecurableObject catalogObject =@@ -617,7 +749,7 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {securableObjects.add(catalogObject);SecurableObject schemaObject =SecurableObjects.ofSchema(- catalogObject, SCHEMA_NAME, ImmutableList.of(Privileges.UseSchema.allow()));+ catalogObject, schema, ImmutableList.of(Privileges.UseSchema.allow()));securableObjects.add(schemaObject);SecurableObject tableObject =SecurableObjects.ofTable(@@ -635,10 +767,13 @@ public class IcebergTableAuthorizationIT extends IcebergAuthorizationIT {}private void setTableOwner(String tableName) {+ setTableOwner(SCHEMA_NAME, tableName);+ }++ private void setTableOwner(String schema, String tableName) {MetadataObject tableMetadataObject =MetadataObjects.of(- Arrays.asList(GRAVITINO_CATALOG_NAME, SCHEMA_NAME, tableName),- MetadataObject.Type.TABLE);+ Arrays.asList(GRAVITINO_CATALOG_NAME, schema, tableName), MetadataObject.Type.TABLE);metalakeClientWithAllPrivilege.setOwner(tableMetadataObject, NORMAL_USER, Owner.Type.USER);}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergViewAuthorizationIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergViewAuthorizationIT.javaindex 2ffd92c8e2..ef4295b392 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergViewAuthorizationIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergViewAuthorizationIT.java@@ -118,6 +118,155 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {() -> sql("CREATE VIEW %s AS SELECT * FROM %s", viewName3, fullTableName(BASE_TABLE_NAME)));}+ @Test+ void testCreateViewInNestedNamespace() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested";+ String nestedBaseTable = "nested_base_table";+ String nestedView = "test_nested_view";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested"}, nestedBaseTable);+ grantUseSchemaRole(nestedSchemaInGravitino);+ sql("USE %s;", nestedSchemaInIceberg);++ Assertions.assertThrowsExactly(+ ForbiddenException.class,+ () -> sql("CREATE VIEW %s AS SELECT * FROM %s", nestedView, nestedBaseTable));++ String createViewRole = grantCreateViewRole(nestedSchemaInGravitino);+ String selectTableRole = grantSelectTableRole(nestedSchemaInGravitino, nestedBaseTable);+ Assertions.assertDoesNotThrow(+ () -> sql("CREATE VIEW %s AS SELECT * FROM %s", nestedView, nestedBaseTable));++ Optional<Owner> owner =+ metalakeClientWithAllPrivilege.getOwner(+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedSchemaInGravitino, nestedView),+ MetadataObject.Type.VIEW));+ Assertions.assertTrue(owner.isPresent());+ Assertions.assertEquals(NORMAL_USER, owner.get().name());++ revokeRole(createViewRole);+ revokeRole(selectTableRole);+ }++ @Test+ void testCreateViewInNestedNamespaceWithInheritedParentPrivilege() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested_inherit";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_inherit";+ String nestedBaseTable = "nested_inherited_base_table";+ String nestedView = "test_nested_inherited_view";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_inherit");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested_inherit"}, nestedBaseTable);++ Assertions.assertThrowsExactly(+ ForbiddenException.class,+ () -> {+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE VIEW %s AS SELECT * FROM %s", nestedView, nestedBaseTable);+ });++ String createViewRole = grantCreateViewRole(SCHEMA_NAME);+ String selectTableRole = grantSelectTableOnSchemaRole(SCHEMA_NAME);+ Assertions.assertDoesNotThrow(+ () -> {+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE VIEW %s AS SELECT * FROM %s", nestedView, nestedBaseTable);+ },+ "Schema-level privileges on parent namespace should be inherited by child namespace");++ Optional<Owner> owner =+ metalakeClientWithAllPrivilege.getOwner(+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedSchemaInGravitino, nestedView),+ MetadataObject.Type.VIEW));+ Assertions.assertTrue(owner.isPresent());+ Assertions.assertEquals(NORMAL_USER, owner.get().name());++ revokeRole(createViewRole);+ revokeRole(selectTableRole);+ }++ @Test+ void testLoadReplaceDropViewInNestedNamespace() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested_crud";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_crud";+ String nestedBaseTable = "nested_crud_base_table";+ String nestedView = "nested_crud_view";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_crud");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested_crud"}, nestedBaseTable);+ grantUseSchemaRole(nestedSchemaInGravitino);+ String createViewRole = grantCreateViewRole(nestedSchemaInGravitino);+ String selectTableRole = grantSelectTableRole(nestedSchemaInGravitino, nestedBaseTable);+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE VIEW %s AS SELECT * FROM %s", nestedView, nestedBaseTable);+ revokeRole(createViewRole);+ revokeRole(selectTableRole);++ Assertions.assertThrowsExactly(+ ForbiddenException.class, () -> sql("SELECT * FROM %s", nestedView));++ String selectViewRole = grantSelectViewRole(nestedSchemaInGravitino, nestedView);+ String selectBaseTableRole = grantSelectTableRole(nestedSchemaInGravitino, nestedBaseTable);+ Assertions.assertDoesNotThrow(() -> sql("SELECT * FROM %s", nestedView));+ revokeRole(selectViewRole);+ revokeRole(selectBaseTableRole);++ setSchemaOwner(SCHEMA_NAME, NORMAL_USER);+ Assertions.assertDoesNotThrow(+ () ->+ sql("CREATE OR REPLACE VIEW %s AS SELECT col_1 FROM %s", nestedView, nestedBaseTable));+ Assertions.assertDoesNotThrow(() -> sql("DROP VIEW %s", nestedView));+ setSchemaOwner(SCHEMA_NAME, SUPER_USER);+ }++ @Test+ void testListNestedNamespaceViewsWithInheritedParentPrivilege() {+ String nestedSchemaInGravitino = SCHEMA_NAME + ":nested_list";+ String nestedSchemaInIceberg = SCHEMA_NAME + ".nested_list";+ String nestedBaseTable = "nested_list_base_table";+ String view1 = "nested_list_view_1";+ String view2 = "nested_list_view_2";++ createNestedNamespaceViaIRC(SCHEMA_NAME, "nested_list");+ createTableViaIRC(new String[] {SCHEMA_NAME, "nested_list"}, nestedBaseTable);+ setSchemaOwner(SCHEMA_NAME, NORMAL_USER);+ sql("USE %s;", nestedSchemaInIceberg);+ sql("CREATE VIEW %s AS SELECT * FROM %s", view1, nestedBaseTable);+ sql("CREATE VIEW %s AS SELECT col_1 FROM %s", view2, nestedBaseTable);++ // Creator is the view owner, so both nested views are visible.+ Set<String> viewNames = listViewNames(nestedSchemaInIceberg);+ Assertions.assertEquals(2, viewNames.size());+ Assertions.assertTrue(viewNames.contains(view1));+ Assertions.assertTrue(viewNames.contains(view2));++ // Transfer ownership away to verify inherited parent privilege behavior.+ MetadataObject view1MetadataObject =+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedSchemaInGravitino, view1),+ MetadataObject.Type.VIEW);+ MetadataObject view2MetadataObject =+ MetadataObjects.of(+ Arrays.asList(GRAVITINO_CATALOG_NAME, nestedSchemaInGravitino, view2),+ MetadataObject.Type.VIEW);+ metalakeClientWithAllPrivilege.setOwner(view1MetadataObject, SUPER_USER, Owner.Type.USER);+ metalakeClientWithAllPrivilege.setOwner(view2MetadataObject, SUPER_USER, Owner.Type.USER);+ setSchemaOwner(SCHEMA_NAME, SUPER_USER);++ viewNames = listViewNames(nestedSchemaInIceberg);+ Assertions.assertEquals(0, viewNames.size());++ setSchemaOwner(SCHEMA_NAME, NORMAL_USER);+ viewNames = listViewNames(nestedSchemaInIceberg);+ Assertions.assertTrue(viewNames.contains(view1));+ Assertions.assertTrue(viewNames.contains(view2));+ setSchemaOwner(SCHEMA_NAME, SUPER_USER);+ }+@Testvoid testCreateViewRequiresSelectOnUnderlyingTable() {String viewName = "test_invoker_create_view";@@ -533,6 +682,10 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {}private String grantSelectViewRole(String viewName) {+ return grantSelectViewRole(SCHEMA_NAME, viewName);+ }++ private String grantSelectViewRole(String schema, String viewName) {String roleName = "selectView_" + UUID.randomUUID();List<SecurableObject> securableObjects = new ArrayList<>();SecurableObject catalogObject =@@ -541,7 +694,7 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {securableObjects.add(catalogObject);SecurableObject schemaObject =SecurableObjects.ofSchema(- catalogObject, SCHEMA_NAME, ImmutableList.of(Privileges.UseSchema.allow()));+ catalogObject, schema, ImmutableList.of(Privileges.UseSchema.allow()));securableObjects.add(schemaObject);SecurableObject viewObject =SecurableObjects.ofView(@@ -553,6 +706,28 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {}private String grantSelectTableRole(String tableName) {+ return grantSelectTableRole(SCHEMA_NAME, tableName);+ }++ private String grantSelectTableOnSchemaRole(String schema) {+ String roleName = "selectTableOnSchema_" + UUID.randomUUID();+ List<SecurableObject> securableObjects = new ArrayList<>();+ SecurableObject catalogObject =+ SecurableObjects.ofCatalog(+ GRAVITINO_CATALOG_NAME, ImmutableList.of(Privileges.UseCatalog.allow()));+ securableObjects.add(catalogObject);+ SecurableObject schemaObject =+ SecurableObjects.ofSchema(+ catalogObject,+ schema,+ ImmutableList.of(Privileges.UseSchema.allow(), Privileges.SelectTable.allow()));+ securableObjects.add(schemaObject);+ metalakeClientWithAllPrivilege.createRole(roleName, new HashMap<>(), securableObjects);+ metalakeClientWithAllPrivilege.grantRolesToUser(ImmutableList.of(roleName), NORMAL_USER);+ return roleName;+ }++ private String grantSelectTableRole(String schema, String tableName) {String roleName = "selectTable_" + UUID.randomUUID();List<SecurableObject> securableObjects = new ArrayList<>();SecurableObject catalogObject =@@ -561,7 +736,7 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {securableObjects.add(catalogObject);SecurableObject schemaObject =SecurableObjects.ofSchema(- catalogObject, SCHEMA_NAME, ImmutableList.of(Privileges.UseSchema.allow()));+ catalogObject, schema, ImmutableList.of(Privileges.UseSchema.allow()));securableObjects.add(schemaObject);SecurableObject tableObject =SecurableObjects.ofTable(@@ -586,9 +761,13 @@ public class IcebergViewAuthorizationIT extends IcebergAuthorizationIT {}private void setSchemaOwner(String userName) {+ setSchemaOwner(SCHEMA_NAME, userName);+ }++ private void setSchemaOwner(String schema, String userName) {MetadataObject schemaMetadataObject =MetadataObjects.of(- Arrays.asList(GRAVITINO_CATALOG_NAME, SCHEMA_NAME), MetadataObject.Type.SCHEMA);+ Arrays.asList(GRAVITINO_CATALOG_NAME, schema), MetadataObject.Type.SCHEMA);metalakeClientWithAllPrivilege.setOwner(schemaMetadataObject, userName, Owner.Type.USER);}}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.javaindex 792f85fba1..275fa49b50 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java@@ -19,21 +19,33 @@package org.apache.gravitino.iceberg.service.dispatcher;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import com.google.common.collect.ImmutableSet;import java.util.Arrays;+import java.util.List;+import java.util.Set;+import java.util.stream.Collectors;import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.catalog.SchemaDispatcher;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;import org.apache.gravitino.listener.api.event.IcebergRequestContext;+import org.apache.gravitino.lock.LockManager;+import org.apache.gravitino.lock.TreeLock;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;import org.apache.iceberg.rest.requests.RegisterTableRequest;@@ -43,6 +55,7 @@ import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;public class TestIcebergNamespaceHookDispatcher {@@ -53,6 +66,8 @@ public class TestIcebergNamespaceHookDispatcher {private IcebergNamespaceHookDispatcher hookDispatcher;private IcebergNamespaceOperationDispatcher mockDispatcher;private OwnerDispatcher mockOwnerDispatcher;+ private EntityStore mockEntityStore;+ private LockManager mockLockManager;private IcebergRequestContext mockContext;@BeforeEach@@ -67,6 +82,14 @@ public class TestIcebergNamespaceHookDispatcher {GravitinoEnv.getInstance(), "schemaDispatcher", mockSchemaDispatcher, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "tableDispatcher", mockTableDispatcher, true);+ mockEntityStore = mock(EntityStore.class);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "entityStore", mockEntityStore, true);++ mockLockManager = mock(LockManager.class);+ TreeLock mockTreeLock = mock(TreeLock.class);+ when(mockLockManager.createTreeLock(any())).thenReturn(mockTreeLock);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", mockLockManager, true);+IcebergConfigProvider mockConfigProvider = mock(IcebergConfigProvider.class);when(mockConfigProvider.getMetalakeName()).thenReturn(TEST_METALAKE);when(mockConfigProvider.getDefaultCatalogName()).thenReturn(TEST_CATALOG);@@ -84,6 +107,8 @@ public class TestIcebergNamespaceHookDispatcher {FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", null, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "schemaDispatcher", null, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "tableDispatcher", null, true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "entityStore", null, true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", null, true);Class<?> holderClass =Arrays.stream(IcebergRESTServerContext.class.getDeclaredClasses())@@ -104,7 +129,7 @@ public class TestIcebergNamespaceHookDispatcher {doThrow(new RuntimeException("Set owner failed")).when(mockOwnerDispatcher)- .setOwner(any(), any(), any(), any());+ .setOwners(any(), any(), any(), any());RuntimeException thrown =Assertions.assertThrows(@@ -154,7 +179,7 @@ public class TestIcebergNamespaceHookDispatcher {RuntimeException.class, () -> hookDispatcher.createNamespace(mockContext, mockRequest));Assertions.assertEquals("Import failed", thrown.getMessage());- verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ verify(mockOwnerDispatcher, never()).setOwners(any(), any(), any(), any());}@Test@@ -180,4 +205,96 @@ public class TestIcebergNamespaceHookDispatcher {Assertions.assertEquals("Import failed", thrown.getMessage());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}++ @Test+ public void testCreateNamespaceLocksTopLevelBranchRoot() {+ // Lock target must be the top-level branch root (metalake.catalog.A), not the catalog —+ // that's what lets disjoint top-level branches create in parallel.+ Namespace leaf = Namespace.of("A", "B", "C");+ CreateNamespaceRequest request = mock(CreateNamespaceRequest.class);+ when(request.namespace()).thenReturn(leaf);+ when(mockDispatcher.createNamespace(mockContext, request))+ .thenReturn(mock(CreateNamespaceResponse.class));++ hookDispatcher.createNamespace(mockContext, request);++ ArgumentCaptor<NameIdentifier> lockId = ArgumentCaptor.forClass(NameIdentifier.class);+ verify(mockLockManager).createTreeLock(lockId.capture());+ Assertions.assertArrayEquals(+ new String[] {TEST_METALAKE, TEST_CATALOG}, lockId.getValue().namespace().levels());+ Assertions.assertEquals("A", lockId.getValue().name());+ }++ @Test+ public void testCreateNestedNamespaceOwnsMissingAncestorsAndLeaf() {+ // Depth-4 leaf, only A exists. Expect setOwners with [A:B, A:B:C, A:B:C:D] —+ // missing ancestors (outermost first) + leaf; existing A is not re-owned.+ Namespace leaf = Namespace.of("A", "B", "C", "D");+ Set<String> existing = ImmutableSet.of("A");+ when(mockDispatcher.namespaceExists(eq(mockContext), any(Namespace.class)))+ .thenAnswer(+ inv -> {+ Namespace ns = inv.getArgument(1, Namespace.class);+ return existing.contains(String.join(":", ns.levels()));+ });++ CreateNamespaceRequest request = mock(CreateNamespaceRequest.class);+ when(request.namespace()).thenReturn(leaf);+ when(mockDispatcher.createNamespace(mockContext, request))+ .thenReturn(mock(CreateNamespaceResponse.class));++ hookDispatcher.createNamespace(mockContext, request);++ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<MetadataObject>> captor = ArgumentCaptor.forClass(List.class);+ verify(mockOwnerDispatcher)+ .setOwners(eq(TEST_METALAKE), captor.capture(), eq(TEST_USER), eq(Owner.Type.USER));+ List<String> names =+ captor.getValue().stream().map(MetadataObject::fullName).collect(Collectors.toList());+ Assertions.assertEquals(+ Arrays.asList(TEST_CATALOG + ".A:B", TEST_CATALOG + ".A:B:C", TEST_CATALOG + ".A:B:C:D"),+ names);+ }++ @Test+ public void testDropNamespaceDeletesTargetAndPhantomAncestors() throws Exception {+ Namespace leaf = Namespace.of("A", "B", "C");+ Namespace parent = Namespace.of("A", "B");+ Namespace grandparent = Namespace.of("A");++ hookDispatcher.dropNamespace(mockContext, leaf);++ verify(mockDispatcher).dropNamespace(mockContext, leaf);+ verify(mockDispatcher, never()).dropNamespace(mockContext, parent);+ verify(mockDispatcher, never()).dropNamespace(mockContext, grandparent);++ ArgumentCaptor<NameIdentifier> captor = ArgumentCaptor.forClass(NameIdentifier.class);+ verify(mockEntityStore, org.mockito.Mockito.times(3))+ .delete(captor.capture(), eq(Entity.EntityType.SCHEMA));+ List<String> deletedNames =+ captor.getAllValues().stream().map(NameIdentifier::name).collect(Collectors.toList());+ Assertions.assertEquals(Arrays.asList("A:B:C", "A:B", "A"), deletedNames);+ }++ @Test+ public void testDropNamespaceDeletesTargetWhenAncestorsExist() throws Exception {+ Namespace leaf = Namespace.of("A", "B", "C");+ Namespace parent = Namespace.of("A", "B");+ Namespace grandparent = Namespace.of("A");++ when(mockDispatcher.namespaceExists(mockContext, parent)).thenReturn(true);++ hookDispatcher.dropNamespace(mockContext, leaf);++ verify(mockDispatcher).dropNamespace(mockContext, leaf);+ verify(mockDispatcher, never()).dropNamespace(mockContext, parent);+ verify(mockDispatcher, never()).dropNamespace(mockContext, grandparent);+ verify(mockDispatcher).namespaceExists(mockContext, parent);+ verify(mockDispatcher, never()).namespaceExists(mockContext, grandparent);++ ArgumentCaptor<NameIdentifier> captor = ArgumentCaptor.forClass(NameIdentifier.class);+ verify(mockEntityStore, org.mockito.Mockito.times(1))+ .delete(captor.capture(), eq(Entity.EntityType.SCHEMA));+ Assertions.assertEquals("A:B:C", captor.getValue().name());+ }}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.javaindex 89f5b3929e..f9cb7353ba 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java@@ -24,6 +24,8 @@ import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.util.Arrays;+import java.util.Collections;import java.util.HashMap;import java.util.Map;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;@@ -33,6 +35,8 @@ import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;import org.apache.iceberg.rest.responses.CreateNamespaceResponse;+import org.apache.iceberg.rest.responses.GetNamespaceResponse;+import org.apache.iceberg.rest.responses.ListNamespacesResponse;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -134,4 +138,110 @@ public class TestIcebergNamespaceOperationExecutor {String actualOwner = requestCaptor.getValue().properties().get(IcebergConstants.OWNER);Assertions.assertEquals(clientProvidedOwner, actualOwner);}++ @Test+ public void testCreateMultiLevelNamespacePassesCorrectNamespace() {+ String authenticatedUser = "[email protected]";+ Namespace multiLevelNs = Namespace.of("team", "sales");++ CreateNamespaceRequest originalRequest =+ CreateNamespaceRequest.builder().withNamespace(multiLevelNs).build();++ when(mockContext.userName()).thenReturn(authenticatedUser);+ CreateNamespaceResponse mockResponse = mock(CreateNamespaceResponse.class);+ when(mockCatalogWrapper.createNamespace(any())).thenReturn(mockResponse);++ executor.createNamespace(mockContext, originalRequest);++ ArgumentCaptor<CreateNamespaceRequest> requestCaptor =+ ArgumentCaptor.forClass(CreateNamespaceRequest.class);+ verify(mockCatalogWrapper).createNamespace(requestCaptor.capture());++ CreateNamespaceRequest capturedRequest = requestCaptor.getValue();+ Assertions.assertEquals(multiLevelNs, capturedRequest.namespace());+ Assertions.assertEquals(+ authenticatedUser, capturedRequest.properties().get(IcebergConstants.OWNER));+ }++ @Test+ public void testLoadNamespaceDelegatesToCatalogWrapper() {+ Namespace ns = Namespace.of("A", "B");+ GetNamespaceResponse mockResponse = mock(GetNamespaceResponse.class);+ when(mockCatalogWrapper.loadNamespace(ns)).thenReturn(mockResponse);++ GetNamespaceResponse result = executor.loadNamespace(mockContext, ns);++ verify(mockCatalogWrapper).loadNamespace(ns);+ Assertions.assertEquals(mockResponse, result);+ }++ @Test+ public void testDropNestedNamespacePassesCorrectLevels() {+ Namespace nestedNs = Namespace.of("A", "B", "C");++ executor.dropNamespace(mockContext, nestedNs);++ verify(mockCatalogWrapper).dropNamespace(nestedNs);+ }++ @Test+ public void testDropFlatNamespaceDelegatesToCatalogWrapper() {+ Namespace ns = Namespace.of("mydb");++ executor.dropNamespace(mockContext, ns);++ verify(mockCatalogWrapper).dropNamespace(ns);+ }++ @Test+ public void testListNamespacesWithParentDelegatesToCatalogWrapper() {+ Namespace parent = Namespace.of("A", "B");+ Namespace child = Namespace.of("A", "B", "C");+ ListNamespacesResponse mockResponse =+ ListNamespacesResponse.builder().addAll(Collections.singletonList(child)).build();+ when(mockCatalogWrapper.listNamespace(parent)).thenReturn(mockResponse);++ ListNamespacesResponse result = executor.listNamespaces(mockContext, parent);++ verify(mockCatalogWrapper).listNamespace(parent);+ Assertions.assertEquals(mockResponse, result);+ Assertions.assertEquals(Arrays.asList(child), result.namespaces());+ }++ @Test+ public void testListNamespacesAtRootLevelDelegatesToCatalogWrapper() {+ Namespace root = Namespace.empty();+ Namespace ns1 = Namespace.of("A");+ Namespace ns2 = Namespace.of("B");+ ListNamespacesResponse mockResponse =+ ListNamespacesResponse.builder().addAll(Arrays.asList(ns1, ns2)).build();+ when(mockCatalogWrapper.listNamespace(root)).thenReturn(mockResponse);++ ListNamespacesResponse result = executor.listNamespaces(mockContext, root);++ verify(mockCatalogWrapper).listNamespace(root);+ Assertions.assertEquals(2, result.namespaces().size());+ }++ @Test+ public void testNamespaceExistsDelegatesToCatalogWrapper() {+ Namespace nestedNs = Namespace.of("A", "B");+ when(mockCatalogWrapper.namespaceExists(nestedNs)).thenReturn(true);++ boolean exists = executor.namespaceExists(mockContext, nestedNs);++ verify(mockCatalogWrapper).namespaceExists(nestedNs);+ Assertions.assertTrue(exists);+ }++ @Test+ public void testNamespaceNotExistsDelegatesToCatalogWrapper() {+ Namespace ns = Namespace.of("nonexistent");+ when(mockCatalogWrapper.namespaceExists(ns)).thenReturn(false);++ boolean exists = executor.namespaceExists(mockContext, ns);++ verify(mockCatalogWrapper).namespaceExists(ns);+ Assertions.assertFalse(exists);+ }}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnershipUtils.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnershipUtils.javaindex 6415a8f066..775405817c 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnershipUtils.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnershipUtils.java@@ -20,12 +20,22 @@package org.apache.gravitino.iceberg.service.dispatcher;import static org.junit.jupiter.api.Assertions.fail;+import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;-+import static org.mockito.Mockito.when;++import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;import org.apache.gravitino.Entity.EntityType;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.authorization.Owner;@@ -34,6 +44,7 @@ import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;@@ -47,19 +58,30 @@ public class TestIcebergOwnershipUtils {private static final String SCHEMA_NAME = "test_schema";private static final String TABLE_NAME = "test_table";private static final String VIEW_NAME = "test_view";+ private static final String SEPARATOR = ":";private OwnerDispatcher mockOwnerDispatcher;+ private Config previousConfig;@BeforeEach- public void setUp() {+ public void setUp() throws IllegalAccessException {mockOwnerDispatcher = mock(OwnerDispatcher.class);+ Config mockConfig = mock(Config.class);+ when(mockConfig.get(Configs.SCHEMA_SEPARATOR)).thenReturn(SEPARATOR);+ previousConfig = (Config) FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", mockConfig, true);+ }++ @AfterEach+ public void tearDown() throws IllegalAccessException {+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previousConfig, true);}@Testpublic void testSetSchemaOwner() {Namespace namespace = Namespace.of(SCHEMA_NAME);NameIdentifier expectedSchemaIdentifier =- IcebergIdentifierUtils.toGravitinoSchemaIdentifier(METALAKE, CATALOG, namespace);+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(METALAKE, CATALOG, namespace, SEPARATOR);MetadataObject expectedMetadataObject =NameIdentifierUtil.toMetadataObject(expectedSchemaIdentifier, EntityType.SCHEMA);@@ -74,7 +96,8 @@ public class TestIcebergOwnershipUtils {Namespace namespace = Namespace.of(SCHEMA_NAME);TableIdentifier tableIdentifier = TableIdentifier.of(namespace, TABLE_NAME);NameIdentifier expectedTableIdentifier =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, tableIdentifier);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ METALAKE, CATALOG, tableIdentifier, SEPARATOR);MetadataObject expectedMetadataObject =NameIdentifierUtil.toMetadataObject(expectedTableIdentifier, EntityType.TABLE);@@ -85,6 +108,47 @@ public class TestIcebergOwnershipUtils {.setOwner(eq(METALAKE), eq(expectedMetadataObject), eq(USER), eq(Owner.Type.USER));}+ @Test+ public void testSetSchemaOwnersBatch() {+ Namespace nsA = Namespace.of("A");+ Namespace nsAB = Namespace.of("A", "B");+ MetadataObject objectA =+ NameIdentifierUtil.toMetadataObject(+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(METALAKE, CATALOG, nsA, SEPARATOR),+ EntityType.SCHEMA);+ MetadataObject objectAB =+ NameIdentifierUtil.toMetadataObject(+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(METALAKE, CATALOG, nsAB, SEPARATOR),+ EntityType.SCHEMA);++ IcebergOwnershipUtils.setSchemaOwners(+ METALAKE, CATALOG, Arrays.asList(nsA, nsAB), USER, mockOwnerDispatcher);++ List<MetadataObject> expected = Arrays.asList(objectA, objectAB);+ verify(mockOwnerDispatcher, times(1))+ .setOwners(eq(METALAKE), eq(expected), eq(USER), eq(Owner.Type.USER));+ }++ @Test+ public void testSetSchemaOwnersWithEmptyCollectionIsNoOp() {+ IcebergOwnershipUtils.setSchemaOwners(+ METALAKE, CATALOG, Collections.emptyList(), USER, mockOwnerDispatcher);++ verify(mockOwnerDispatcher, never()).setOwners(any(), any(), any(), any());+ verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ }++ @Test+ public void testSetSchemaOwnersWithNullOwnerDispatcher() {+ try {+ IcebergOwnershipUtils.setSchemaOwners(+ METALAKE, CATALOG, Collections.singletonList(Namespace.of(SCHEMA_NAME)), USER, null);+ } catch (Exception e) {+ fail(+ "setSchemaOwners should handle null dispatcher gracefully, but threw: " + e.getMessage());+ }+ }+@Testpublic void testSetSchemaOwnerWithNullOwnerDispatcher() {Namespace namespace = Namespace.of(SCHEMA_NAME);@@ -112,7 +176,8 @@ public class TestIcebergOwnershipUtils {Namespace namespace = Namespace.of(SCHEMA_NAME);TableIdentifier viewIdentifier = TableIdentifier.of(namespace, VIEW_NAME);NameIdentifier expectedViewIdentifier =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdentifier);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ METALAKE, CATALOG, viewIdentifier, SEPARATOR);MetadataObject expectedMetadataObject =NameIdentifierUtil.toMetadataObject(expectedViewIdentifier, EntityType.VIEW);diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.javaindex cc5f915475..6b03109c94 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java@@ -32,6 +32,8 @@ import java.util.Arrays;import java.util.Collections;import java.util.List;import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;@@ -77,6 +79,11 @@ public class TestIcebergTableHookDispatcher {private OwnerDispatcher mockOwnerDispatcher;private IcebergRequestContext mockContext;+ private Config previousConfig;+ private EntityStore previousEntityStore;+ private TableDispatcher previousTableDispatcher;+ private OwnerDispatcher previousOwnerDispatcher;+@BeforeEachpublic void setUp() throws IllegalAccessException {// Mock the underlying dispatcher@@ -87,6 +94,16 @@ public class TestIcebergTableHookDispatcher {mockTableDispatcher = mock(TableDispatcher.class);mockOwnerDispatcher = mock(OwnerDispatcher.class);+ Config mockConfig = mock(Config.class);+ when(mockConfig.get(Configs.SCHEMA_SEPARATOR)).thenReturn(":");+ previousConfig = (Config) FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);+ previousEntityStore =+ (EntityStore) FieldUtils.readField(GravitinoEnv.getInstance(), "entityStore", true);+ previousTableDispatcher =+ (TableDispatcher) FieldUtils.readField(GravitinoEnv.getInstance(), "tableDispatcher", true);+ previousOwnerDispatcher =+ (OwnerDispatcher) FieldUtils.readField(GravitinoEnv.getInstance(), "ownerDispatcher", true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", mockConfig, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "entityStore", mockEntityStore, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "tableDispatcher", mockTableDispatcher, true);FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", mockOwnerDispatcher, true);@@ -108,10 +125,14 @@ public class TestIcebergTableHookDispatcher {@AfterEachpublic void tearDown() throws IllegalAccessException {- // Clean up GravitinoEnv- FieldUtils.writeField(GravitinoEnv.getInstance(), "entityStore", null, true);- FieldUtils.writeField(GravitinoEnv.getInstance(), "tableDispatcher", null, true);- FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", null, true);+ // Restore GravitinoEnv to its prior state so this test doesn't leak singleton state+ // into other tests that share the same JVM.+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previousConfig, true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "entityStore", previousEntityStore, true);+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "tableDispatcher", previousTableDispatcher, true);+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "ownerDispatcher", previousOwnerDispatcher, true);// Reset IcebergRESTServerContext singletonClass<?> holderClass =@@ -139,7 +160,7 @@ public class TestIcebergTableHookDispatcher {// Verify table import was calledNameIdentifier expectedIdentifier =IcebergIdentifierUtils.toGravitinoTableIdentifier(- TEST_METALAKE, TEST_CATALOG, TableIdentifier.of(namespace, "test_table"));+ TEST_METALAKE, TEST_CATALOG, TableIdentifier.of(namespace, "test_table"), ":");verify(mockTableDispatcher).loadTable(expectedIdentifier);// Verify ownership was set@@ -158,7 +179,8 @@ public class TestIcebergTableHookDispatcher {verify(mockDispatcher).dropTable(mockContext, tableId, false);NameIdentifier expectedIdentifier =- IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, tableId, ":");verify(mockEntityStore).delete(expectedIdentifier, Entity.EntityType.TABLE);}@@ -167,7 +189,8 @@ public class TestIcebergTableHookDispatcher {TableIdentifier tableId = TableIdentifier.of("test_schema", "test_table");NameIdentifier expectedIdentifier =- IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, tableId, ":");doThrow(new NoSuchEntityException("Table not found")).when(mockEntityStore).delete(expectedIdentifier, Entity.EntityType.TABLE);@@ -214,7 +237,7 @@ public class TestIcebergTableHookDispatcher {verify(mockDispatcher).renameTable(mockContext, request);NameIdentifier sourceIdentifier =- IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, source);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, source, ":");verify(mockEntityStore).update(eq(sourceIdentifier), eq(TableEntity.class), eq(Entity.EntityType.TABLE), any());}@@ -315,12 +338,11 @@ public class TestIcebergTableHookDispatcher {Assertions.assertEquals(mockResponse, result);verify(mockDispatcher).updateTable(mockContext, tableId, request);- // Verify table import was calledNameIdentifier gravitinoTableId =- IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, tableId, ":");verify(mockTableDispatcher).loadTable(gravitinoTableId);- // Verify ownership was setArgumentCaptor<String> userCaptor = ArgumentCaptor.forClass(String.class);verify(mockOwnerDispatcher).setOwner(eq(TEST_METALAKE), any(), userCaptor.capture(), eq(Owner.Type.USER));diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.javaindex 195f7673e3..45faf33f9b 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java@@ -31,6 +31,8 @@ import static org.mockito.Mockito.when;import java.io.IOException;import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;@@ -76,6 +78,11 @@ public class TestIcebergViewHookDispatcher {private IcebergRequestContext mockContext;private GravitinoEnv gravitinoEnv;+ private Config previousConfig;+ private EntityStore previousEntityStore;+ private ViewDispatcher previousViewDispatcher;+ private OwnerDispatcher previousOwnerDispatcher;+@BeforeEachpublic void setUp() {mockExecutor = mock(IcebergViewOperationDispatcher.class);@@ -90,6 +97,15 @@ public class TestIcebergViewHookDispatcher {// Setup GravitinoEnv mockgravitinoEnv = GravitinoEnv.getInstance();try {+ Config mockConfig = mock(Config.class);+ when(mockConfig.get(Configs.SCHEMA_SEPARATOR)).thenReturn(":");+ previousConfig = (Config) FieldUtils.readField(gravitinoEnv, "config", true);+ previousEntityStore = (EntityStore) FieldUtils.readField(gravitinoEnv, "entityStore", true);+ previousViewDispatcher =+ (ViewDispatcher) FieldUtils.readField(gravitinoEnv, "viewDispatcher", true);+ previousOwnerDispatcher =+ (OwnerDispatcher) FieldUtils.readField(gravitinoEnv, "ownerDispatcher", true);+ FieldUtils.writeField(gravitinoEnv, "config", mockConfig, true);FieldUtils.writeField(gravitinoEnv, "entityStore", mockEntityStore, true);FieldUtils.writeField(gravitinoEnv, "viewDispatcher", mockViewDispatcher, true);FieldUtils.writeField(gravitinoEnv, "ownerDispatcher", mockOwnerDispatcher, true);@@ -103,10 +119,12 @@ public class TestIcebergViewHookDispatcher {@AfterEachpublic void tearDown() {try {- // Clean up GravitinoEnv- FieldUtils.writeField(gravitinoEnv, "entityStore", null, true);- FieldUtils.writeField(gravitinoEnv, "viewDispatcher", null, true);- FieldUtils.writeField(gravitinoEnv, "ownerDispatcher", null, true);+ // Restore GravitinoEnv to its prior state so this test doesn't leak singleton state+ // into other tests that share the same JVM.+ FieldUtils.writeField(gravitinoEnv, "config", previousConfig, true);+ FieldUtils.writeField(gravitinoEnv, "entityStore", previousEntityStore, true);+ FieldUtils.writeField(gravitinoEnv, "viewDispatcher", previousViewDispatcher, true);+ FieldUtils.writeField(gravitinoEnv, "ownerDispatcher", previousOwnerDispatcher, true);} catch (Exception e) {// Ignore cleanup errors}@@ -235,7 +253,7 @@ public class TestIcebergViewHookDispatcher {// Verify view was deleted from entity storeNameIdentifier expectedIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent, ":");verify(mockEntityStore, times(1)).delete(eq(expectedIdent), eq(Entity.EntityType.VIEW));}@@ -245,7 +263,7 @@ public class TestIcebergViewHookDispatcher {// Simulate entity not found in storeNameIdentifier expectedIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent, ":");doThrow(new NoSuchEntityException("Entity not found")).when(mockEntityStore).delete(eq(expectedIdent), eq(Entity.EntityType.VIEW));@@ -263,7 +281,7 @@ public class TestIcebergViewHookDispatcher {// Simulate IO errorNameIdentifier expectedIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent, ":");doThrow(new IOException("IO error")).when(mockEntityStore).delete(eq(expectedIdent), eq(Entity.EntityType.VIEW));@@ -290,7 +308,7 @@ public class TestIcebergViewHookDispatcher {// Verify entity store was updatedNameIdentifier sourceGravitinoIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent, ":");verify(mockEntityStore, times(1)).update(eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any());}@@ -304,7 +322,7 @@ public class TestIcebergViewHookDispatcher {// Simulate entity not found in storeNameIdentifier sourceGravitinoIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent, ":");when(mockEntityStore.update(eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any())).thenThrow(new NoSuchEntityException("Entity not found"));@@ -324,7 +342,7 @@ public class TestIcebergViewHookDispatcher {// Simulate IO errorNameIdentifier sourceGravitinoIdent =- IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);+ IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent, ":");when(mockEntityStore.update(eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any())).thenThrow(new IOException("IO error"));diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergMetadataAuthorizationMethodInterceptor.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergMetadataAuthorizationMethodInterceptor.javaindex 5db3cca4af..f5d9852b01 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergMetadataAuthorizationMethodInterceptor.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergMetadataAuthorizationMethodInterceptor.java@@ -31,7 +31,11 @@ import java.util.Map;import java.util.Optional;import javax.ws.rs.core.Response;import org.aopalliance.intercept.MethodInvocation;+import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;@@ -41,6 +45,7 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationExpresimport org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.catalog.Catalog;+import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.exceptions.ForbiddenException;import org.apache.iceberg.rest.RESTCatalog;import org.apache.iceberg.rest.RESTUtil;@@ -176,6 +181,66 @@ public class TestIcebergMetadataAuthorizationMethodInterceptor {assertFalse(interceptor.isExceptionPropagate(otherException));}+ @Test+ public void testExtractNestedSchemaNamespace() throws Exception {+ IcebergMetadataAuthorizationMethodInterceptor interceptor =+ new IcebergMetadataAuthorizationMethodInterceptor();++ Method testMethod =+ TestOperations.class.getMethod(+ "testTableOperation", String.class, String.class, String.class);+ Parameter[] parameters = testMethod.getParameters();++ String encodedNamespace = RESTUtil.encodeNamespace(Namespace.of("A", "B", "C"));+ Object[] args = new Object[] {TEST_CATALOG + "/", encodedNamespace, "my_table"};++ Config mockConfig = Mockito.mock(Config.class);+ Mockito.when(mockConfig.get(Configs.SCHEMA_SEPARATOR)).thenReturn(":");+ Config previousConfig =+ (Config) FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", mockConfig, true);+ try {+ Map<Entity.EntityType, NameIdentifier> nameIdentifierMap =+ interceptor.extractNameIdentifierFromParameters(parameters, args);++ NameIdentifier schemaId = nameIdentifierMap.get(Entity.EntityType.SCHEMA);+ assertNotNull(schemaId);+ assertEquals("A:B:C", schemaId.name());+ } finally {+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previousConfig, true);+ }+ }++ @Test+ public void testExtractFlatSchemaNamespace() throws Exception {+ IcebergMetadataAuthorizationMethodInterceptor interceptor =+ new IcebergMetadataAuthorizationMethodInterceptor();++ Method testMethod =+ TestOperations.class.getMethod(+ "testTableOperation", String.class, String.class, String.class);+ Parameter[] parameters = testMethod.getParameters();++ String encodedNamespace = RESTUtil.encodeNamespace(Namespace.of("my_schema"));+ Object[] args = new Object[] {TEST_CATALOG + "/", encodedNamespace, "my_table"};++ Config mockConfig = Mockito.mock(Config.class);+ Mockito.when(mockConfig.get(Configs.SCHEMA_SEPARATOR)).thenReturn(":");+ Config previousConfig =+ (Config) FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", mockConfig, true);+ try {+ Map<Entity.EntityType, NameIdentifier> nameIdentifierMap =+ interceptor.extractNameIdentifierFromParameters(parameters, args);++ NameIdentifier schemaId = nameIdentifierMap.get(Entity.EntityType.SCHEMA);+ assertNotNull(schemaId);+ assertEquals("my_schema", schemaId.name());+ } finally {+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previousConfig, true);+ }+ }+@Testpublic void testInvokeSkipsAuthorizationForRestCatalog() throws Throwable {IcebergCatalogWrapperManager wrapperManager = Mockito.mock(IcebergCatalogWrapperManager.class);diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.javaindex 41febe5218..5f7a5695a2 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.util.Map;+import java.util.Optional;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;@@ -33,6 +34,7 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.CapabilityHelpers;import org.apache.gravitino.catalog.CatalogManager;import org.apache.gravitino.connector.capability.Capability;+import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.utils.EntityClassMapper;import org.apache.gravitino.utils.MetadataObjectUtil;@@ -56,9 +58,9 @@ public class MetadataIdConverter {** @param metadataObject The metadata object to convert.* @param metalake The metalake name.- * @return The metadata id.+ * @return The metadata id, empty if metadata does not exist.*/- public static Long getID(MetadataObject metadataObject, String metalake) {+ public static Optional<Long> getID(MetadataObject metadataObject, String metalake) {Preconditions.checkArgument(metadataObject != null, "Metadata object cannot be null");EntityStore entityStore = GravitinoEnv.getInstance().entityStore();CatalogManager catalogManager = GravitinoEnv.getInstance().catalogManager();@@ -76,12 +78,14 @@ public class MetadataIdConverter {entity =entityStore.get(normalizedIdent, entityType, EntityClassMapper.getEntityClass(entityType));+ } catch (NoSuchEntityException nse) {+ return Optional.empty();} catch (IOException e) {throw new RuntimeException("failed to load entity from entity store: " + metadataObject.fullName(), e);}- return extractIdFromEntity(entity);+ return Optional.of(extractIdFromEntity(entity));}@VisibleForTestingdiff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.javaindex 4507ba0a50..4a4a58a599 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java@@ -243,8 +243,8 @@ public class AuthorizationExpressionConverter {expression =expression.replaceAll("ANY_CREATE_SCHEMA",- "((ANY(CREATE_SCHEMA, METALAKE, CATALOG)) "- + "&& !(ANY(DENY_CREATE_SCHEMA, METALAKE, CATALOG)))");+ "((ANY(CREATE_SCHEMA, METALAKE, CATALOG, SCHEMA)) "+ + "&& !(ANY(DENY_CREATE_SCHEMA, METALAKE, CATALOG, SCHEMA)))");expression =expression.replaceAll("ANY_SELECT_TABLE",diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.javaindex f9171bd72e..1877e3e1da 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java@@ -23,6 +23,7 @@ import java.util.Optional;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.authorization.AuthorizationRequestContext;import org.apache.gravitino.cache.GravitinoCache;+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.server.authorization.MetadataIdConverter;import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;@@ -65,15 +66,32 @@ public class JcasbinAuthorizationLookups {/*** Two-tier name→id lookup: the per-request map in {@code requestContext} dedups calls within the* same HTTP request; on a miss, the long-lived {@code metadataIdCache} is consulted, and finally- * we fall back to a DB query via {@link MetadataIdConverter#getID}.+ * we fall back to a DB query via {@link MetadataIdConverter#getID}. Returns {@link+ * Optional#empty()} when the metadata object does not exist so callers can deny authorization; a+ * missing object is never cached as a negative result.*/- public Long resolveMetadataId(+ public Optional<Long> resolveMetadataId(MetadataObject metadataObject, String metalake, AuthorizationRequestContext requestContext) {String cacheKey = buildCacheKey(metalake, metadataObject);- return requestContext.computeMetadataIdIfAbsent(- cacheKey,- k ->- metadataIdCache.get(k, ignored -> MetadataIdConverter.getID(metadataObject, metalake)));+ try {+ // Both cache tiers load atomically and forbid caching null, so a missing object is signalled+ // by throwing through the loaders and translated back to Optional.empty() here. This caches+ // only positive results, never a negative one.+ return Optional.of(+ requestContext.computeMetadataIdIfAbsent(+ cacheKey,+ k -> metadataIdCache.get(k, ignored -> loadMetadataId(metadataObject, metalake))));+ } catch (NoSuchMetadataObjectException e) {+ return Optional.empty();+ }+ }++ private static Long loadMetadataId(MetadataObject metadataObject, String metalake) {+ return MetadataIdConverter.getID(metadataObject, metalake)+ .orElseThrow(+ () ->+ new NoSuchMetadataObjectException(+ "Metadata object %s does not exist", metadataObject.fullName()));}/**diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.javaindex 2929bf7415..1f6b28aa85 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java@@ -64,6 +64,7 @@ import org.apache.gravitino.meta.RoleEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.server.authorization.MetadataIdConverter;import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.casbin.jcasbin.main.Enforcer;@@ -249,16 +250,29 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {String metalake,MetadataObject metadataObject,AuthorizationRequestContext requestContext) {- boolean result;- try {- Long metadataId = lookups.resolveMetadataId(metadataObject, metalake, requestContext);- Optional<OwnerInfo> owner =- lookups.resolveOwnerId(metadataId, metadataObject.type(), requestContext);- result = ownerMatchesUserOrGroups(owner, principal, metalake);- } catch (Exception e) {- LOG.debug("Can not get entity id", e);- result = false;+ boolean result = false;+ // The metadataObject is resolved from an OGNL variable (e.g. SCHEMA, CATALOG) bound from the+ // request context when the authorization expression is evaluated. It can be null when the+ // expression references a metadata-object type that is not present for the current request,+ // so we treat a missing object as "not the owner".+ if (metadataObject == null) {+ return false;+ }++ if (metadataObject.type() == MetadataObject.Type.SCHEMA) {+ // We support hierarchical schema, so a schema may have ancestor schemas. The principal is+ // treated as the owner if it owns the schema itself or any of its ancestor schemas, hence we+ // walk the whole inheritance chain here.+ for (MetadataObject scopeObject : buildSchemaInheritanceChain(metadataObject)) {+ if (isOwnerOfObject(scopeObject, principal, metalake, requestContext)) {+ result = true;+ break;+ }+ }+ } else {+ result = isOwnerOfObject(metadataObject, principal, metalake, requestContext);}+LOG.debug("Authorization expression: {},privilege {},owner result {}\n,principal {},metalake {},metadata object {}",requestContext.getOriginalAuthorizationExpression(),@@ -270,6 +284,25 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {return result;}+ /**+ * Resolves the owner of a single metadata object via the cache-backed lookups and checks whether+ * the given principal (directly or through one of its groups) is that owner. A missing object is+ * treated as "not the owner".+ */+ private boolean isOwnerOfObject(+ MetadataObject metadataObject,+ Principal principal,+ String metalake,+ AuthorizationRequestContext requestContext) {+ Optional<Long> metadataId = lookups.resolveMetadataId(metadataObject, metalake, requestContext);+ if (!metadataId.isPresent()) {+ return false;+ }+ Optional<OwnerInfo> owner =+ lookups.resolveOwnerId(metadataId.get(), metadataObject.type(), requestContext);+ return ownerMatchesUserOrGroups(owner, principal, metalake);+ }+@Overridepublic boolean isServiceAdmin() {return GravitinoEnv.getInstance()@@ -301,9 +334,12 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {return Objects.equals(nameIdentifier.name(), currentUserName);} else if (Entity.EntityType.ROLE == type) {try {- Long roleId =+ Optional<Long> roleId =MetadataIdConverter.getID(NameIdentifierUtil.toMetadataObject(nameIdentifier, type), metalake);+ if (!roleId.isPresent()) {+ return false;+ }EntityStore entityStore = GravitinoEnv.getInstance().entityStore();NameIdentifier userNameIdentifier =NameIdentifierUtil.ofUser(metalake, PrincipalUtils.getCurrentUserName());@@ -314,14 +350,16 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {SupportsRelationOperations.Type.ROLE_USER_REL,userNameIdentifier,Entity.EntityType.USER);+ long resolvedRoleId = roleId.get();// Check direct user-role assignment- if (entities.stream().anyMatch(roleEntity -> Objects.equals(roleEntity.id(), roleId))) {+ if (entities.stream()+ .anyMatch(roleEntity -> Objects.equals(roleEntity.id(), resolvedRoleId))) {return true;}// Check group-role assignments.for (GroupEntity groupEntity : resolveCurrentUserGroups(metalake, entityStore)) {List<Long> groupRoleIds = groupEntity.roleIds();- if (groupRoleIds != null && groupRoleIds.contains(roleId)) {+ if (groupRoleIds != null && groupRoleIds.contains(resolvedRoleId)) {return true;}}@@ -451,8 +489,7 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {// name->id mapping as well to prevent using a stale metadataId from metadataIdCache.metadataIdCache.invalidate(JcasbinAuthorizationLookups.buildCacheKey(metalake, metadataObject));try {- Long metadataId = MetadataIdConverter.getID(metadataObject, metalake);- ownerRelCache.invalidate(metadataId);+ MetadataIdConverter.getID(metadataObject, metalake).ifPresent(ownerRelCache::invalidate);} catch (RuntimeException e) {LOG.warn("Failed to resolve metadata id for owner cache invalidation: {}", metadataObject, e);}@@ -498,6 +535,28 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {}}+ /**+ * Builds the logical schema inheritance chain for a SCHEMA MetadataObject, ordered from the+ * outermost ancestor to the schema itself. For a schema object whose parent is {@code catalog}+ * and whose name is {@code "A:B:C"}, this returns MetadataObjects for parent {@code catalog} with+ * schema names {@code A}, {@code A:B}, and {@code A:B:C} in that order so that an ancestor-level+ * privilege grant short-circuits the authorization check before descending into more specific+ * scopes.+ *+ * <p>For flat (non-HierarchicalSchema) schemas the list contains only the original object.+ */+ private List<MetadataObject> buildSchemaInheritanceChain(MetadataObject schemaObject) {+ String separator = HierarchicalSchemaUtil.schemaSeparator();++ List<String> scopes = HierarchicalSchemaUtil.allScopes(schemaObject.name(), separator);+ List<MetadataObject> chain = new ArrayList<>(scopes.size());+ for (int i = scopes.size() - 1; i >= 0; i--) {+ chain.add(+ MetadataObjects.of(schemaObject.parent(), scopes.get(i), MetadataObject.Type.SCHEMA));+ }+ return ImmutableList.copyOf(chain);+ }+private class InternalAuthorizer {Enforcer enforcer;@@ -522,19 +581,55 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {MetadataObject metadataObject,String privilege,AuthorizationRequestContext requestContext) {- Long metadataId;Long userId;try {UserEntity userEntity = getUserEntity(username, metalake);userId = userEntity.id();- metadataId = lookups.resolveMetadataId(metadataObject, metalake, requestContext);} catch (Exception e) {LOG.debug("Can not get entity id", e);return false;}loadRolePrivilege(metalake, username, userId, requestContext);++ // For requests such as CREATE SCHEMA, the metadata object may be null. This method+ // performs object-scoped authorization, so without a metadata object it cannot evaluate+ // the request and must deny authorization here.+ if (metadataObject == null) {+ return false;+ }+ // For SCHEMA objects with hierarchical schema names (for example, parent=catalog and+ // name="A:B:C"), walk the logical parent chain from the outermost ancestor down to the+ // schema itself so that a privilege granted on an ancestor schema short-circuits the check+ // before descending into more specific scopes.+ if (metadataObject.type() == MetadataObject.Type.SCHEMA) {+ for (MetadataObject scopeObject : buildSchemaInheritanceChain(metadataObject)) {+ if (authorizeObject(userId, metalake, scopeObject, privilege, requestContext)) {+ return true;+ }+ }+ return false;+ }++ return authorizeObject(userId, metalake, metadataObject, privilege, requestContext);+ }++ /**+ * Resolves the metadata id for a single object via the cache-backed lookups and delegates to+ * {@link #authorizeByJcasbin}. A missing object is treated as "not authorized".+ */+ private boolean authorizeObject(+ Long userId,+ String metalake,+ MetadataObject metadataObject,+ String privilege,+ AuthorizationRequestContext requestContext) {+ Optional<Long> metadataId =+ lookups.resolveMetadataId(metadataObject, metalake, requestContext);+ if (!metadataId.isPresent()) {+ return false;+ }return authorizeByJcasbin(- userId, metalake, metadataObject, metadataId, privilege, requestContext);+ userId, metalake, metadataObject, metadataId.get(), privilege, requestContext);}private boolean authorizeByJcasbin(@@ -587,7 +682,13 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {for (RoleEntity role : entities) {desiredRoleIds.add(String.valueOf(role.id()));addRoleForUserAndLoadPolicies(- userId, metalake, role.id(), role.name(), loadRoleFutures, entityStore);+ userId,+ metalake,+ role.id(),+ role.name(),+ loadRoleFutures,+ entityStore,+ requestContext);}// Load roles inherited from the user's groups.@@ -613,7 +714,8 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {roleIds.get(i),roleNames.get(i),loadRoleFutures,- entityStore);+ entityStore,+ requestContext);}}@@ -666,7 +768,8 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {Long roleId,String roleName,List<CompletableFuture<Void>> loadRoleFutures,- EntityStore entityStore) {+ EntityStore entityStore,+ AuthorizationRequestContext requestContext) {allowEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));denyEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));if (loadedRoles.getIfPresent(roleId) != null) {@@ -687,25 +790,32 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {executor).thenAcceptAsync(roleEntity -> {- loadPolicyByRoleEntity(roleEntity);+ loadPolicyByRoleEntity(roleEntity, requestContext);loadedRoles.put(roleId, true);},executor);loadRoleFutures.add(loadRoleFuture);}- private void loadPolicyByRoleEntity(RoleEntity roleEntity) {+ private void loadPolicyByRoleEntity(+ RoleEntity roleEntity, AuthorizationRequestContext requestContext) {String metalake = NameIdentifierUtil.getMetalake(roleEntity.nameIdentifier());List<SecurableObject> securableObjects = roleEntity.securableObjects();for (SecurableObject securableObject : securableObjects) {+ Optional<Long> metadataId =+ lookups.resolveMetadataId(securableObject, metalake, requestContext);+ // A role may still reference a metadata object that has since been dropped; skip it.+ if (!metadataId.isPresent()) {+ continue;+ }for (Privilege privilege : securableObject.privileges()) {Privilege.Condition condition = privilege.condition();if (AuthConstants.DENY.equalsIgnoreCase(condition.name())) {denyEnforcer.addPolicy(String.valueOf(roleEntity.id()),securableObject.type().name(),- String.valueOf(MetadataIdConverter.getID(securableObject, metalake)),+ String.valueOf(metadataId.get()),AuthorizationUtils.replaceLegacyPrivilegeName(privilege.name()).name().toUpperCase(java.util.Locale.ROOT),@@ -722,7 +832,7 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {allowEnforcer.addPolicy(String.valueOf(roleEntity.id()),securableObject.type().name(),- String.valueOf(MetadataIdConverter.getID(securableObject, metalake)),+ String.valueOf(metadataId.get()),AuthorizationUtils.replaceLegacyPrivilegeName(privilege.name()).name().toUpperCase(java.util.Locale.ROOT),diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.javaindex e2f2e5686d..4a11a0a152 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java@@ -29,6 +29,7 @@ import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.time.Instant;+import java.util.Optional;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.Entity;@@ -151,46 +152,46 @@ public class TestMetadataIdConverter {eq(ident8), eq(null), eq(mockCatalogManager))).thenReturn(ident8);- Long metalakeConvertedId =+ Optional<Long> metalakeConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("metalake"), MetadataObject.Type.METALAKE),"metalake");- Long catalogConvertedId =+ Optional<Long> catalogConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog"), MetadataObject.Type.CATALOG),"metalake");- Long schemaConvertedId =+ Optional<Long> schemaConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog", "schema"), MetadataObject.Type.SCHEMA),"metalake");- Long tableConvertedId =+ Optional<Long> tableConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog", "schema", "table"), MetadataObject.Type.TABLE),"metalake");- Long modelConvertedId =+ Optional<Long> modelConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog", "schema", "model"), MetadataObject.Type.MODEL),"metalake");- Long filesetConvertedId =+ Optional<Long> filesetConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog", "schema", "fileset"), MetadataObject.Type.FILESET),"metalake");- Long topicConvertedId =+ Optional<Long> topicConvertedId =MetadataIdConverter.getID(MetadataObjects.of(ImmutableList.of("catalog", "schema", "topic"), MetadataObject.Type.TOPIC),"metalake");- Assertions.assertEquals(1L, metalakeConvertedId);- Assertions.assertEquals(2L, catalogConvertedId);- Assertions.assertEquals(3L, schemaConvertedId);- Assertions.assertEquals(4L, tableConvertedId);- Assertions.assertEquals(5L, modelConvertedId);- Assertions.assertEquals(6L, filesetConvertedId);- Assertions.assertEquals(7L, topicConvertedId);+ Assertions.assertEquals(Optional.of(1L), metalakeConvertedId);+ Assertions.assertEquals(Optional.of(2L), catalogConvertedId);+ Assertions.assertEquals(Optional.of(3L), schemaConvertedId);+ Assertions.assertEquals(Optional.of(4L), tableConvertedId);+ Assertions.assertEquals(Optional.of(5L), modelConvertedId);+ Assertions.assertEquals(Optional.of(6L), filesetConvertedId);+ Assertions.assertEquals(Optional.of(7L), topicConvertedId);} finally {FieldUtils.writeDeclaredField(GravitinoEnv.getInstance(), "catalogManager", originalCatalogManager, true);diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.javaindex da033695c9..5772d23ccd 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java@@ -120,4 +120,13 @@ public class TestAuthorizationExpressionConverter {AuthorizationExpressionConverter.replaceAnyExpressions("(ANY(OWNER, METALAKE, CATALOG)) && CATALOG::USE_CATALOG"));}++ @Test+ public void testReplaceAnyPrivilegeForAnyCreateSchemaIncludesSchemaAndDeny() {+ String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_CREATE_SCHEMA");+ Assertions.assertEquals(+ "((ANY(CREATE_SCHEMA, METALAKE, CATALOG, SCHEMA)) "+ + "&& !(ANY(DENY_CREATE_SCHEMA, METALAKE, CATALOG, SCHEMA)))",+ replaced);+ }}diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.javaindex cfab7f8010..afbf9f3685 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java@@ -130,8 +130,10 @@ public class TestJcasbinAuthorizationLookups {new JcasbinAuthorizationLookups(metadataIdCache, ownerRelCache);AuthorizationRequestContext requestContext = new AuthorizationRequestContext();- Assertions.assertEquals(100L, lookups.resolveMetadataId(table, "ml1", requestContext));- Assertions.assertEquals(100L, lookups.resolveMetadataId(table, "ml1", requestContext));+ Assertions.assertEquals(+ Optional.of(100L), lookups.resolveMetadataId(table, "ml1", requestContext));+ Assertions.assertEquals(+ Optional.of(100L), lookups.resolveMetadataId(table, "ml1", requestContext));Assertions.assertEquals(1, metadataIdCache.getCount);Assertions.assertEquals(0, metadataIdCache.getIfPresentCount);diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.javaindex 3e65d4fb4a..e1dea19922 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java@@ -177,7 +177,7 @@ public class TestJcasbinAuthorizer {principalUtilsMockedStatic.when(PrincipalUtils::getCurrentUserName).thenCallRealMethod();metadataIdConverterMockedStatic.when(() -> MetadataIdConverter.getID(any(), eq(METALAKE)))- .thenReturn(CATALOG_ID);+ .thenReturn(Optional.of(CATALOG_ID));when(gravitinoEnv.entityStore()).thenReturn(entityStore);when(entityStore.relationOperations()).thenReturn(supportsRelationOperations);when(entityStore.get(@@ -1068,7 +1068,7 @@ public class TestJcasbinAuthorizer {} finally {metadataIdConverterMockedStatic.when(() -> MetadataIdConverter.getID(any(), eq(METALAKE)))- .thenReturn(CATALOG_ID);+ .thenReturn(Optional.of(CATALOG_ID));}}