World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14243] fix(iceberg): Authorize staged-create commits with CREATE_TABLE (#14908)
roryqi93c453e24f59
diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.javaindex 72de829bff..c15c1739a1 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java@@ -21,6 +21,7 @@ import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLClassLoader;+import java.net.URLConnection;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@@ -197,12 +198,19 @@ public final class HiveClientClassLoader extends URLClassLoader {private Class<?> loadBarrierClass(String name) throws ClassNotFoundException {LOG.debug("Classloader {} loading barrier class {}", getName(), name);String classFileName = name.replace(".", "/") + ".class";- try (InputStream is = baseClassLoader.getResourceAsStream(classFileName)) {- if (is == null) {- throw new ClassNotFoundException("Cannot load barrier class: " + name);+ URL resource = baseClassLoader.getResource(classFileName);+ if (resource == null) {+ throw new ClassNotFoundException("Cannot load barrier class: " + name);+ }+ try {+ URLConnection connection = resource.openConnection();+ // Another catalog loader can close the same cached JarFile during catalog replacement.+ // Keep this read independent, and release its JAR handle when the stream closes.+ connection.setUseCaches(false);+ try (InputStream is = connection.getInputStream()) {+ byte[] bytes = is.readAllBytes();+ return defineClass(name, bytes, 0, bytes.length);}- byte[] bytes = is.readAllBytes();- return defineClass(name, bytes, 0, bytes.length);} catch (IOException e) {throw new ClassNotFoundException("Failed to load barrier class: " + name, e);}diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveClientClassLoader.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveClientClassLoader.javaindex 2cb98de374..e9aa4a5d76 100644--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveClientClassLoader.java+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveClientClassLoader.java@@ -19,20 +19,91 @@package org.apache.gravitino.hive.client;+import java.io.IOException;+import java.io.InputStream;import java.lang.reflect.Field;import java.lang.reflect.Method;+import java.net.URL;+import java.net.URLClassLoader;+import java.net.URLConnection;+import java.net.URLStreamHandler;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Map;import java.util.Properties;+import java.util.jar.JarEntry;+import java.util.jar.JarOutputStream;import org.apache.hadoop.conf.Configuration;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.spi.LoggerContext;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;import org.slf4j.ILoggerFactory;import org.slf4j.LoggerFactory;public class TestHiveClientClassLoader {+ @Test+ void testBarrierClassLoadsWhileAnotherCatalogCloses(@TempDir Path tempDir) throws Exception {+ String className = HiveShim.class.getName();+ String resourceName = className.replace('.', '/') + ".class";+ ClassLoader applicationLoader = getClass().getClassLoader();+ Path jar = tempDir.resolve("hive-client.jar");+ try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar));+ InputStream input = applicationLoader.getResourceAsStream(resourceName)) {+ Assertions.assertNotNull(input);+ output.putNextEntry(new JarEntry(resourceName));+ input.transferTo(output);+ output.closeEntry();+ }++ try (URLClassLoader retiringLoader = new URLClassLoader(new URL[] {jar.toUri().toURL()}, null);+ InputStream cachedStream = retiringLoader.getResourceAsStream(resourceName)) {+ Assertions.assertNotNull(cachedStream);+ URL resource = retiringLoader.getResource(resourceName);+ // Close the old catalog after the new one opens its stream, reproducing cache eviction+ // during catalog replacement without relying on thread timing.+ URL closingResource =+ new URL(+ null,+ resource.toString(),+ new URLStreamHandler() {+ @Override+ protected URLConnection openConnection(URL url) throws IOException {+ URLConnection delegate = resource.openConnection();+ return new URLConnection(url) {+ @Override+ public void connect() throws IOException {+ delegate.connect();+ }++ @Override+ public InputStream getInputStream() throws IOException {+ delegate.setUseCaches(getUseCaches());+ InputStream input = delegate.getInputStream();+ retiringLoader.close();+ return input;+ }+ };+ }+ });+ ClassLoader baseLoader =+ new ClassLoader(applicationLoader) {+ @Override+ public URL getResource(String name) {+ return resourceName.equals(name) ? closingResource : super.getResource(name);+ }+ };+ try (HiveClientClassLoader loader =+ HiveClientClassLoader.createLoader(HiveClientClassLoader.HiveVersion.HIVE3, baseLoader)) {+ Class<?> loaded = loader.loadClass(className);+ Assertions.assertEquals(className, loaded.getName());+ Assertions.assertSame(loader, loaded.getClassLoader());+ }+ }+ }+@Testvoid testCloseRemovesLog4jLoggerContextRegistration() throws Exception {HiveClientClassLoader classLoader =diff --git a/docs/gravitino-server-config.md b/docs/gravitino-server-config.mdindex 8d62c78662..8b667c33a0 100644--- a/docs/gravitino-server-config.md+++ b/docs/gravitino-server-config.md@@ -220,6 +220,24 @@ It adds the OAuth client settings when `oauth` is among the authenticators. Treathrough `visibleConfigs` as public, and only add properties that a client needs before it canauthenticate.+Set `gravitino.server.visibleConfigs` when a Web UI or another client needs extra server+configuration, for example to use the server's session timeout settings rather than local UI+defaults. Set both the property values and the comma-separated list of keys in+`conf/gravitino.conf`, then restart the server:++```properties+gravitino.ui.sessionIdleTimeoutMs = 1800000+gravitino.ui.sessionMaxDurationMs = 28800000+gravitino.server.visibleConfigs = gravitino.ui.sessionIdleTimeoutMs,gravitino.ui.sessionMaxDurationMs+```++Clients can then read those values from `GET http://localhost:8090/configs`. A key with no+explicitly configured value is omitted. Leave the list empty when clients do not need additional+settings; the fixed configuration keys are still returned. This setting controls configuration+visibility, not access to catalogs or other metadata. Never include passwords, tokens, client+secrets, or administrator lists. See [Web UI session settings](webui-v2.md#session-timeout-configuration) for the+UI's configuration lookup order.+Two further groups of `gravitino.server.webserver.*` properties are documented elsewhere, becausethey belong to features rather than to the web server itself. TLS, key stores, trust stores, andclient certificate authentication are in [HTTPS](security/how-to-use-https.md). The CORS filterdiff --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 21b2245c05..797d8a67bd 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@@ -173,10 +173,7 @@ public class IcebergTableOperations {@Timed(name = "create-table." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "create-table", absolute = true)@AuthorizationExpression(- expression =- "ANY(OWNER, METALAKE, CATALOG) || "- + "SCHEMA_OWNER_WITH_USE_CATALOG || "- + "ANY_USE_CATALOG && ANY_USE_SCHEMA && ANY_CREATE_TABLE",+ expression = AuthorizationExpressionConstants.CREATE_TABLE_AUTHORIZATION_EXPRESSION,accessMetadataType = MetadataObject.Type.SCHEMA)public Response createTable(@AuthorizationMetadata(type = Entity.EntityType.CATALOG) @PathParam("prefix") String prefix,@@ -226,7 +223,8 @@ public class IcebergTableOperations {String namespace,@AuthorizationMetadata(type = Entity.EntityType.TABLE) @Encoded() @PathParam("table")String table,- UpdateTableRequest updateTableRequest) {+ @IcebergAuthorizationMetadata(type = IcebergAuthorizationMetadata.RequestType.UPDATE_TABLE)+ UpdateTableRequest updateTableRequest) {IcebergRESTUtils.validateRequest(updateTableRequest, "UpdateTableRequest");String catalogName = IcebergRESTUtils.getCatalogName(prefix);Namespace icebergNS =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 2e2a3dba01..e5e76caaca 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@@ -35,6 +35,8 @@ public @interface IcebergAuthorizationMetadata {RENAME_VIEW,CREATE_NAMESPACE,REGISTER_TABLE,+ /** A table commit that may complete staged creation. */+ UPDATE_TABLE,}/*** 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/IcebergMetadataAuthorizationMethodInterceptor.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.javaindex 756c64b2a3..42617eec78 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@@ -47,6 +47,7 @@ import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.rest.RESTUtil;+import org.apache.iceberg.rest.requests.UpdateTableRequest;/*** Through dynamic proxy, obtain the annotations on the method and parameter list to perform@@ -168,7 +169,8 @@ public class IcebergMetadataAuthorizationMethodInterceptorObject[] args,Map<Entity.EntityType, NameIdentifier> nameIdentifierMap) {AuthorizationExpression authExpr = method.getAnnotation(AuthorizationExpression.class);- for (Parameter parameter : parameters) {+ for (int i = 0; i < parameters.length; i++) {+ Parameter parameter = parameters[i];IcebergAuthorizationMetadata icebergMetadata =parameter.getAnnotation(IcebergAuthorizationMetadata.class);if (icebergMetadata != null) {@@ -185,6 +187,8 @@ public class IcebergMetadataAuthorizationMethodInterceptorreturn Optional.of(new RenameViewAuthzHandler(parameters, args));case CREATE_NAMESPACE:return Optional.of(new CreateNamespaceAuthzHandler(parameters, args));+ case UPDATE_TABLE:+ return Optional.of(new UpdateTableAuthzHandler((UpdateTableRequest) args[i]));case REGISTER_TABLE:return Optional.of(new RegisterTableAuthzHandler(parameters, args, nameIdentifierMap));default:diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.javanew file mode 100644index 0000000000..8c34f603f0--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java@@ -0,0 +1,84 @@+/*+ * 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 static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CREATE_TABLE_AUTHORIZATION_EXPRESSION;++import java.util.HashMap;+import java.util.Map;+import java.util.Optional;+import org.apache.gravitino.Entity.EntityType;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.authorization.AuthorizationRequestContext;+import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;+import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;+import org.apache.iceberg.UpdateRequirement;+import org.apache.iceberg.rest.requests.UpdateTableRequest;++/**+ * Authorizes staged table creation against the schema before Iceberg executes the commit.+ *+ * <p>Iceberg still validates {@code AssertTableDoesNotExist} at commit time, so this creation+ * authorization cannot replace an existing table, including one created after authorization.+ * Location is part of the new table's creation metadata; the executor's owner-property guard+ * separately sets a supplied owner to the authenticated user.+ */+public class UpdateTableAuthzHandler implements AuthorizationHandler {+ private final boolean stagedCreate;++ /**+ * Creates a handler using the same staged-create predicate as the table hook dispatcher.+ *+ * @param request the table commit request+ */+ public UpdateTableAuthzHandler(UpdateTableRequest request) {+ IcebergRESTUtils.validateRequest(request, "UpdateTableRequest");+ stagedCreate =+ request.requirements().stream()+ .anyMatch(UpdateRequirement.AssertTableDoesNotExist.class::isInstance);+ }++ @Override+ public void process(Map<EntityType, NameIdentifier> nameIdentifierMap) {+ if (stagedCreate+ && !new AuthorizationExpressionEvaluator(CREATE_TABLE_AUTHORIZATION_EXPRESSION)+ .evaluate(+ nameIdentifierMap,+ new HashMap<>(),+ new AuthorizationRequestContext(),+ Optional.of(EntityType.SCHEMA.name()))) {+ throw new ForbiddenException(+ "Not authorized to create table in schema '%s'",+ nameIdentifierMap.get(EntityType.SCHEMA));+ }+ }++ @Override+ public boolean authorizationCompleted() {+ // Ordinary commits continue through the endpoint's existing MODIFY_TABLE expression.+ return stagedCreate;+ }++ @Override+ public EntityType entityType() {+ return stagedCreate ? EntityType.SCHEMA : EntityType.TABLE;+ }+}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergCommitValidation.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergCommitValidation.javaindex 2167b55cc8..fa5385f513 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergCommitValidation.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergCommitValidation.java@@ -210,6 +210,43 @@ public class TestIcebergCommitValidation {catalog, staged, IcebergCommitValidation.withValidation(request)));}+ /** A staged create cannot change a table created by another client before the commit. */+ @Test+ public void testStagedCreateCannotReplaceExistingTable() {+ TableIdentifier identifier = TableIdentifier.of("db", "concurrent_create");+ UpdateTableRequest create = stagedCreateRequest(identifier);+ UpdateTableRequest request =+ new UpdateTableRequest(+ create.requirements(),+ ImmutableList.<MetadataUpdate>builder()+ .addAll(create.updates())+ .add(new MetadataUpdate.SetProperties(ImmutableMap.of("owner", "staged_creator")))+ .add(new MetadataUpdate.SetLocation("/data/staged_create"))+ .build());++ // Another client creates the table after staging and before the first client's commit.+ Table existing =+ catalog+ .buildTable(identifier, SCHEMA)+ .withProperty("owner", "other_creator")+ .withLocation("/data/concurrent_create")+ .create();+ TableMetadata before = ((HasTableOperations) existing).operations().current();++ Assertions.assertThrows(+ CommitFailedException.class,+ () ->+ CatalogHandlers.updateTable(+ catalog, identifier, IcebergCommitValidation.withValidation(request)));++ TableMetadata after =+ ((HasTableOperations) catalog.loadTable(identifier)).operations().current();+ Assertions.assertEquals(before.metadataFileLocation(), after.metadataFileLocation());+ Assertions.assertEquals(before.uuid(), after.uuid());+ Assertions.assertEquals(before.properties(), after.properties());+ Assertions.assertEquals(before.location(), after.location());+ }+@Testpublic void testStagedCreateIsValidatedBeforeCommit() {TableIdentifier staged = TableIdentifier.of("db", "invalid_staged");diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestUpdateTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestUpdateTableAuthzHandler.javanew file mode 100644index 0000000000..22832dc378--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestUpdateTableAuthzHandler.java@@ -0,0 +1,227 @@+/*+ * 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 static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.lang.reflect.Method;+import java.util.Collections;+import java.util.List;+import java.util.Set;+import javax.ws.rs.core.Response;+import org.aopalliance.intercept.MethodInvocation;+import org.apache.gravitino.Entity.EntityType;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.authorization.AuthorizationUtils;+import org.apache.gravitino.authorization.GravitinoAuthorizer;+import org.apache.gravitino.authorization.Privilege;+import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;+import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;+import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;+import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;+import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;+import org.apache.gravitino.utils.PrincipalUtils;+import org.apache.iceberg.UpdateRequirement;+import org.apache.iceberg.rest.requests.UpdateTableRequest;+import org.apache.iceberg.rest.responses.ErrorResponse;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;++/** Tests staged-create authorization separately from ordinary table commits. */+class TestUpdateTableAuthzHandler {+ private static final String METALAKE = "test_metalake";+ private static final String CATALOG = "test_catalog";+ private static final String TABLE = "existing_table";+ private static final String PROCEEDED = "PROCEEDED";++ private CatalogWrapperForREST catalogWrapper;+ private GravitinoAuthorizer authorizer;+ private IcebergMetadataAuthorizationMethodInterceptor interceptor;+ private MockedStatic<PrincipalUtils> principalUtils;+ private MockedStatic<AuthorizationUtils> authorizationUtils;+ private MockedStatic<GravitinoAuthorizerProvider> authorizerProvider;++ @BeforeEach+ void setUp() {+ catalogWrapper = mock(CatalogWrapperForREST.class);+ when(catalogWrapper.isRESTCatalog()).thenReturn(false);++ IcebergCatalogWrapperManager wrapperManager = mock(IcebergCatalogWrapperManager.class);+ when(wrapperManager.getCatalogWrapper(CATALOG)).thenReturn(catalogWrapper);++ IcebergConfigProvider configProvider = mock(IcebergConfigProvider.class);+ when(configProvider.getMetalakeName()).thenReturn(METALAKE);+ when(configProvider.getDefaultCatalogName()).thenReturn(CATALOG);+ IcebergRESTServerContext.create(configProvider, true, false, false, wrapperManager);++ authorizer = mock(GravitinoAuthorizer.class);+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);+ principalUtils = mockStatic(PrincipalUtils.class);+ authorizationUtils = mockStatic(AuthorizationUtils.class);+ authorizerProvider = mockStatic(GravitinoAuthorizerProvider.class);++ principalUtils+ .when(PrincipalUtils::getCurrentPrincipal)+ .thenReturn(new UserPrincipal("tester"));+ principalUtils.when(PrincipalUtils::getCurrentUserName).thenReturn("tester");+ authorizerProvider.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);+ when(authorizer.deny(any(), any(), any(), any(), any())).thenReturn(false);+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(false);+ when(authorizer.findUnheldRoles(any(), any(), any(), any())).thenReturn(Set.of());+ interceptor = new IcebergMetadataAuthorizationMethodInterceptor();+ }++ @AfterEach+ void tearDown() {+ authorizerProvider.close();+ authorizationUtils.close();+ principalUtils.close();+ }++ @Test+ void testCreateOnlyUserCanCommitStagedCreate() throws Throwable {+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);+ assertEquals(PROCEEDED, interceptor.invoke(updateInvocation(true)));+ }++ @Test+ void testModifyOnlyUserCannotCreateTable() throws Throwable {+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.MODIFY_TABLE);+ MethodInvocation invocation = updateInvocation(true);+ assertForbidden(interceptor.invoke(invocation));+ verify(invocation, never()).proceed();+ }++ @Test+ void testOrdinaryCommitStillRequiresModifyTable() throws Throwable {+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);+ MethodInvocation invocation = updateInvocation(false);+ assertForbidden(interceptor.invoke(invocation));+ verify(invocation, never()).proceed();+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.MODIFY_TABLE);+ assertEquals(PROCEEDED, interceptor.invoke(updateInvocation(false)));+ }++ @Test+ void testCreateCommitNeedsUseSchemaAndCatalog() throws Throwable {+ allow(Privilege.Name.CREATE_TABLE);+ assertForbidden(interceptor.invoke(updateInvocation(true)));+ allow(Privilege.Name.CREATE_TABLE, Privilege.Name.USE_CATALOG);+ assertForbidden(interceptor.invoke(updateInvocation(true)));+ allow(Privilege.Name.CREATE_TABLE, Privilege.Name.USE_SCHEMA);+ assertForbidden(interceptor.invoke(updateInvocation(true)));+ }++ @Test+ void testDeniedCreateCannotFallBackToModify() throws Throwable {+ allow(+ Privilege.Name.USE_CATALOG,+ Privilege.Name.USE_SCHEMA,+ Privilege.Name.CREATE_TABLE,+ Privilege.Name.MODIFY_TABLE);+ doAnswer(invocation -> invocation.getArgument(3) == Privilege.Name.CREATE_TABLE)+ .when(authorizer)+ .deny(any(), any(), any(), any(), any());+ assertForbidden(interceptor.invoke(updateInvocation(true)));+ }++ @Test+ void testCreateCommitChecksSchemaOwnership() throws Throwable {+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA);+ when(authorizer.isOwner(any(), any(), any(), any()))+ .thenAnswer(+ invocation -> {+ MetadataObject object = invocation.getArgument(2);+ return object != null && object.type() == MetadataObject.Type.TABLE;+ });+ assertForbidden(interceptor.invoke(updateInvocation(true)));+ when(authorizer.isOwner(any(), any(), any(), any()))+ .thenAnswer(+ invocation -> {+ MetadataObject object = invocation.getArgument(2);+ return object != null && object.type() == MetadataObject.Type.SCHEMA;+ });+ assertEquals(PROCEEDED, interceptor.invoke(updateInvocation(true)));+ }++ @Test+ void testStagedCreateRequirementCanAppearAfterOtherRequirements() throws Throwable {+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);+ UpdateTableRequest request =+ new UpdateTableRequest(+ List.of(+ new UpdateRequirement.AssertTableUUID("uuid"),+ new UpdateRequirement.AssertTableDoesNotExist()),+ Collections.emptyList());+ assertEquals(PROCEEDED, interceptor.invoke(updateInvocation(request)));+ }++ @Test+ void testHandlerAttributesCreateDenialToSchema() {+ assertEquals(EntityType.SCHEMA, new UpdateTableAuthzHandler(request(true)).entityType());+ assertEquals(EntityType.TABLE, new UpdateTableAuthzHandler(request(false)).entityType());+ }++ private MethodInvocation updateInvocation(boolean create) throws Throwable {+ return updateInvocation(request(create));+ }++ private MethodInvocation updateInvocation(UpdateTableRequest request) throws Throwable {+ Method method =+ IcebergTableOperations.class.getMethod(+ "updateTable", String.class, String.class, String.class, UpdateTableRequest.class);+ MethodInvocation invocation = mock(MethodInvocation.class);+ when(invocation.getMethod()).thenReturn(method);+ when(invocation.getArguments()).thenReturn(new Object[] {CATALOG + "/", "s1", TABLE, request});+ when(invocation.proceed()).thenReturn(PROCEEDED);+ return invocation;+ }++ private static UpdateTableRequest request(boolean create) {+ return new UpdateTableRequest(+ create ? List.of(new UpdateRequirement.AssertTableDoesNotExist()) : Collections.emptyList(),+ Collections.emptyList());+ }++ private void allow(Privilege.Name... privileges) {+ Set<Privilege.Name> allowed = Set.of(privileges);+ doAnswer(invocation -> allowed.contains(invocation.getArgument(3)))+ .when(authorizer)+ .authorize(any(), any(), any(), any(), any());+ }++ private static void assertForbidden(Object result) {+ Response response = assertInstanceOf(Response.class, result);+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());+ assertInstanceOf(ErrorResponse.class, response.getEntity());+ }+}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.javaindex d32f83bb06..fdbe3f1e8f 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java@@ -102,6 +102,12 @@ public class AuthorizationExpressionConstants {ANY_MODIFY_TABLE || ANY_CREATE_TABLE)""";+ /** Authorizes table creation on the containing schema, including staged-create commits. */+ public static final String CREATE_TABLE_AUTHORIZATION_EXPRESSION =+ "ANY(OWNER, METALAKE, CATALOG) || "+ + "SCHEMA_OWNER_WITH_USE_CATALOG || "+ + "ANY_USE_CATALOG && ANY_USE_SCHEMA && ANY_CREATE_TABLE";+public static final String MODIFY_TABLE_AUTHORIZATION_EXPRESSION ="""ANY(OWNER, METALAKE, CATALOG) ||