World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14444] fix(iceberg-rest): harden authorization, credentials, scans and audit (#14541)
roryqi01eb0c277938
diff --git a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenGenerator.java b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenGenerator.javaindex d234915e2c..ec95898b15 100644--- a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenGenerator.java+++ b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenGenerator.java@@ -19,6 +19,8 @@package org.apache.gravitino.s3.credential;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;import java.io.IOException;import java.net.URI;import java.util.Arrays;@@ -35,8 +37,10 @@ import org.apache.gravitino.credential.PathBasedCredentialContext;import org.apache.gravitino.credential.RoleSessionNameUtils;import org.apache.gravitino.credential.S3TokenCredential;import org.apache.gravitino.credential.config.S3CredentialConfig;+import org.apache.gravitino.storage.S3Properties;import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;import software.amazon.awssdk.policybuilder.iam.IamConditionOperator;import software.amazon.awssdk.policybuilder.iam.IamEffect;@@ -66,7 +70,7 @@ public class S3TokenGenerator implements CredentialGenerator<S3TokenCredential>this.externalID = s3CredentialConfig.externalID();this.tokenExpireSecs = s3CredentialConfig.tokenExpireInSecs();this.listLocationPrefix = s3CredentialConfig.listLocationPrefix();- this.stsClient = createStsClient(s3CredentialConfig);+ this.stsClient = createStsClient(s3CredentialConfig, stsCallerCredentials(properties));}@Override@@ -88,11 +92,32 @@ public class S3TokenGenerator implements CredentialGenerator<S3TokenCredential>s3Token.expiration().toEpochMilli());}- private StsClient createStsClient(S3CredentialConfig s3CredentialConfig) {- AwsCredentialsProvider credentialsProvider =- StaticCredentialsProvider.create(- AwsBasicCredentials.create(- s3CredentialConfig.accessKeyID(), s3CredentialConfig.secretAccessKey()));+ /**+ * Returns the credentials Gravitino uses to call STS. With a static access key pair configured,+ * those keys are used. With neither key configured, the AWS default credential chain is used, so+ * a server running with an instance profile, an EKS service account or environment credentials+ * can assume the vending role without storing keys in the catalog.+ */+ @VisibleForTesting+ static AwsCredentialsProvider stsCallerCredentials(Map<String, String> properties) {+ String accessKeyId = properties.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID);+ String secretAccessKey = properties.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY);+ boolean hasAccessKeyId = StringUtils.isNotBlank(accessKeyId);+ boolean hasSecretAccessKey = StringUtils.isNotBlank(secretAccessKey);+ if (!hasAccessKeyId && !hasSecretAccessKey) {+ return DefaultCredentialsProvider.builder().build();+ }+ Preconditions.checkArgument(+ hasAccessKeyId && hasSecretAccessKey,+ "Set both %s and %s, or neither to use the AWS default credential chain",+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY);+ return StaticCredentialsProvider.create(+ AwsBasicCredentials.create(accessKeyId, secretAccessKey));+ }++ private StsClient createStsClient(+ S3CredentialConfig s3CredentialConfig, AwsCredentialsProvider credentialsProvider) {StsClientBuilder builder = StsClient.builder().credentialsProvider(credentialsProvider);if (StringUtils.isNotBlank(s3CredentialConfig.region())) {diff --git a/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestS3TokenGeneratorCredentials.java b/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestS3TokenGeneratorCredentials.javanew file mode 100644index 0000000000..6169cc129e--- /dev/null+++ b/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestS3TokenGeneratorCredentials.java@@ -0,0 +1,64 @@+/*+ * 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.s3.credential;++import com.google.common.collect.ImmutableMap;+import org.apache.gravitino.storage.S3Properties;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;++/** Tests which credentials the S3 token generator uses to call STS. */+public class TestS3TokenGeneratorCredentials {++ @Test+ public void testStaticKeysAreUsedWhenConfigured() {+ AwsCredentialsProvider provider =+ S3TokenGenerator.stsCallerCredentials(+ ImmutableMap.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID, "AKIAEXAMPLE",+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY, "secret"));+ Assertions.assertInstanceOf(StaticCredentialsProvider.class, provider);+ Assertions.assertEquals("AKIAEXAMPLE", provider.resolveCredentials().accessKeyId());+ }++ @Test+ public void testDefaultChainIsUsedWithoutKeys() {+ // A server running with an instance profile or service account needs no keys in the catalog.+ Assertions.assertInstanceOf(+ DefaultCredentialsProvider.class,+ S3TokenGenerator.stsCallerCredentials(+ ImmutableMap.of(S3Properties.GRAVITINO_S3_ROLE_ARN, "arn:aws:iam::123:role/vend")));+ }++ @Test+ public void testOnlyOneKeyIsRefused() {+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ S3TokenGenerator.stsCallerCredentials(+ ImmutableMap.of(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID, "AKIAEXAMPLE")));+ Assertions.assertTrue(+ e.getMessage().contains(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY), e.getMessage());+ }+}diff --git a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java b/core/src/main/java/org/apache/gravitino/GravitinoEnv.javaindex 3d17fb2b3e..67944e5a9e 100644--- a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java+++ b/core/src/main/java/org/apache/gravitino/GravitinoEnv.java@@ -27,6 +27,7 @@ import org.apache.gravitino.authorization.GravitinoAuthorizer;import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.authorization.OwnerEventManager;import org.apache.gravitino.authorization.OwnerManager;+import org.apache.gravitino.authorization.OwnerPropertySyncDispatcher;import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;import org.apache.gravitino.bulk.BulkManager;import org.apache.gravitino.catalog.CatalogDispatcher;@@ -1173,7 +1174,11 @@ public class GravitinoEnv {new AccessControlHookDispatcher(internalAccessControlDispatcher);this.accessControlDispatcher =new AccessControlEventDispatcher(eventBus, accessControlHookDispatcher);- this.ownerDispatcher = new OwnerEventManager(eventBus, internalOwnerDispatcher);+ // Transfers through the public dispatcher also update the owner property of Iceberg+ // namespaces and tables. Internal callers, such as the Iceberg REST catalog's create hooks,+ // set the first owner, which the property already names.+ this.ownerDispatcher =+ new OwnerEventManager(eventBus, new OwnerPropertySyncDispatcher(internalOwnerDispatcher));} else {this.accessControlDispatcher = null;this.ownerDispatcher = null;diff --git a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java b/core/src/main/java/org/apache/gravitino/audit/AuditLog.javaindex 5dbf1bd2d2..a82c3f1923 100644--- a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java+++ b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java@@ -300,6 +300,8 @@ public interface AuditLog {TABLE_EXISTS,+ REPORT_TABLE_METRICS,+PARTITION_EXIST,ADD_PARTITION,diff --git a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.javaindex 6f70be2f43..5881010fc9 100644--- a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java+++ b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java@@ -62,6 +62,7 @@ public class CompatibilityUtils {.put(OperationType.RENAME_TABLE, Operation.RENAME_TABLE).put(OperationType.REGISTER_TABLE, Operation.REGISTER_TABLE).put(OperationType.TABLE_EXISTS, Operation.TABLE_EXISTS)+ .put(OperationType.REPORT_TABLE_METRICS, Operation.REPORT_TABLE_METRICS).put(OperationType.CREATE_TAG, Operation.CREATE_TAG).put(OperationType.GET_TAG, Operation.GET_TAG).put(OperationType.GET_TAG_FOR_METADATA_OBJECT, Operation.GET_TAG_FOR_METADATA_OBJECT)diff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerPropertySyncDispatcher.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerPropertySyncDispatcher.javanew file mode 100644index 0000000000..4337920152--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerPropertySyncDispatcher.java@@ -0,0 +1,143 @@+/*+ * 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.authorization;++import com.google.common.annotations.VisibleForTesting;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.SchemaChange;+import org.apache.gravitino.catalog.SchemaDispatcher;+import org.apache.gravitino.catalog.TableDispatcher;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.utils.MetadataObjectUtil;+import org.apache.gravitino.utils.NameIdentifierUtil;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Keeps the {@code owner} property of Iceberg namespaces and tables in step with Gravitino+ * ownership. The Iceberg REST catalog writes that property, the conventional Iceberg and Hive owner+ * key that engines display, when it creates a namespace or table. After an ownership transfer this+ * dispatcher rewrites the property to the new owner, so engines and Gravitino give the same answer.+ * Objects without the property, such as those created through the Gravitino API, are left alone.+ */+public class OwnerPropertySyncDispatcher implements OwnerDispatcher {++ /** The Iceberg and Hive property that names an object's owner. */+ @VisibleForTesting static final String OWNER_PROPERTY = "owner";++ private static final Logger LOG = LoggerFactory.getLogger(OwnerPropertySyncDispatcher.class);+ private static final String ICEBERG_PROVIDER = "lakehouse-iceberg";++ private final OwnerDispatcher dispatcher;++ /**+ * Creates a dispatcher that sets owners through {@code dispatcher} and then updates the owner+ * property.+ *+ * @param dispatcher the dispatcher that records ownership+ */+ public OwnerPropertySyncDispatcher(OwnerDispatcher dispatcher) {+ this.dispatcher = dispatcher;+ }++ @Override+ public void setOwner(+ String metalake, MetadataObject metadataObject, String ownerName, Owner.Type ownerType) {+ dispatcher.setOwner(metalake, metadataObject, ownerName, ownerType);+ syncOwnerProperty(metalake, metadataObject, ownerName);+ }++ @Override+ public void setOwners(+ String metalake,+ List<MetadataObject> metadataObjects,+ String ownerName,+ Owner.Type ownerType) {+ dispatcher.setOwners(metalake, metadataObjects, ownerName, ownerType);+ if (metadataObjects != null) {+ metadataObjects.forEach(object -> syncOwnerProperty(metalake, object, ownerName));+ }+ }++ @Override+ public Optional<Owner> getOwner(String metalake, MetadataObject metadataObject) {+ return dispatcher.getOwner(metalake, metadataObject);+ }++ /**+ * Rewrites the owner property of an Iceberg namespace or table that has one. Ownership has+ * already changed when this runs, so a failure is logged rather than failing the transfer.+ */+ @VisibleForTesting+ void syncOwnerProperty(String metalake, MetadataObject metadataObject, String ownerName) {+ MetadataObject.Type type = metadataObject.type();+ if (type != MetadataObject.Type.SCHEMA && type != MetadataObject.Type.TABLE) {+ return;+ }+ NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);+ try {+ if (!isIcebergCatalog(NameIdentifierUtil.getCatalogIdentifier(identifier))) {+ return;+ }+ GravitinoEnv env = GravitinoEnv.getInstance();+ if (type == MetadataObject.Type.SCHEMA) {+ SchemaDispatcher schemas = env.internalSchemaDispatcher();+ Schema schema = schemas.loadSchema(identifier);+ if (needsUpdate(schema.properties(), ownerName)) {+ schemas.alterSchema(identifier, SchemaChange.setProperty(OWNER_PROPERTY, ownerName));+ }+ } else {+ TableDispatcher tables = env.internalTableDispatcher();+ Table table = tables.loadTable(identifier);+ if (needsUpdate(table.properties(), ownerName)) {+ tables.alterTable(identifier, TableChange.setProperty(OWNER_PROPERTY, ownerName));+ }+ }+ } catch (Exception e) {+ LOG.warn(+ "Ownership of {} {} moved to {}, but its {} property could not be updated",+ type,+ identifier,+ ownerName,+ OWNER_PROPERTY,+ e);+ }+ }++ private static boolean isIcebergCatalog(NameIdentifier catalogIdent) {+ Catalog catalog =+ GravitinoEnv.getInstance().internalCatalogDispatcher().loadCatalog(catalogIdent);+ return ICEBERG_PROVIDER.equalsIgnoreCase(catalog.provider());+ }++ @VisibleForTesting+ static boolean needsUpdate(Map<String, String> properties, String ownerName) {+ return properties != null+ && properties.containsKey(OWNER_PROPERTY)+ && !ownerName.equals(properties.get(OWNER_PROPERTY));+ }+}diff --git a/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java b/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.javaindex 9fb5a9eecf..fcfb9a4e43 100644--- a/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java+++ b/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java@@ -67,6 +67,17 @@ public class CatalogCredentialManager implements Closeable {return Optional.ofNullable(credentialProviders.get(credentialType));}+ /**+ * Returns whether a credential provider of this catalog supports the scheme of the path.+ *+ * @param path a storage location+ * @return true if at least one configured provider supports the path's scheme+ */+ public boolean supportsPath(String path) {+ String scheme = extractScheme(path);+ return credentialProviders.values().stream().anyMatch(p -> p.supportsScheme(scheme));+ }+public Optional<Credential> getCredentialByPath(String path, CredentialContext context) {String scheme = extractScheme(path);String matchedCredentialType = null;diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.javaindex 46f351919f..9c23e70ce4 100644--- a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java@@ -33,6 +33,7 @@ public enum OperationType {RENAME_TABLE,REGISTER_TABLE,TABLE_EXISTS,+ REPORT_TABLE_METRICS,// Tag operationsCREATE_TAG,diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerPropertySyncDispatcher.java b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerPropertySyncDispatcher.javanew file mode 100644index 0000000000..5a9f0389b7--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerPropertySyncDispatcher.java@@ -0,0 +1,154 @@+/*+ * 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.authorization;++import static org.mockito.ArgumentMatchers.any;+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.ImmutableMap;+import java.util.Arrays;+import java.util.Collections;+import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.SchemaChange;+import org.apache.gravitino.catalog.CatalogDispatcher;+import org.apache.gravitino.catalog.SchemaDispatcher;+import org.apache.gravitino.catalog.TableDispatcher;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+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.Mockito;++public class TestOwnerPropertySyncDispatcher {++ private static final String METALAKE = "m";+ private static final MetadataObject TABLE =+ MetadataObjects.of(Arrays.asList("cat", "ns", "t"), MetadataObject.Type.TABLE);+ private static final MetadataObject SCHEMA =+ MetadataObjects.of(Arrays.asList("cat", "ns"), MetadataObject.Type.SCHEMA);+ private static final NameIdentifier TABLE_IDENT = NameIdentifier.of(METALAKE, "cat", "ns", "t");+ private static final NameIdentifier SCHEMA_IDENT = NameIdentifier.of(METALAKE, "cat", "ns");++ private final GravitinoEnv env = GravitinoEnv.getInstance();+ private Object previousCatalogs;+ private Object previousSchemas;+ private Object previousTables;+ private OwnerDispatcher delegate;+ private Catalog catalog;+ private SchemaDispatcher schemas;+ private TableDispatcher tables;+ private OwnerPropertySyncDispatcher dispatcher;++ @BeforeEach+ public void setUp() throws IllegalAccessException {+ previousCatalogs = FieldUtils.readField(env, "internalCatalogDispatcher", true);+ previousSchemas = FieldUtils.readField(env, "internalSchemaDispatcher", true);+ previousTables = FieldUtils.readField(env, "internalTableDispatcher", true);+ CatalogDispatcher catalogs = mock(CatalogDispatcher.class);+ catalog = mock(Catalog.class);+ when(catalogs.loadCatalog(NameIdentifier.of(METALAKE, "cat"))).thenReturn(catalog);+ when(catalog.provider()).thenReturn("lakehouse-iceberg");+ schemas = mock(SchemaDispatcher.class);+ tables = mock(TableDispatcher.class);+ FieldUtils.writeField(env, "internalCatalogDispatcher", catalogs, true);+ FieldUtils.writeField(env, "internalSchemaDispatcher", schemas, true);+ FieldUtils.writeField(env, "internalTableDispatcher", tables, true);+ delegate = mock(OwnerDispatcher.class);+ dispatcher = new OwnerPropertySyncDispatcher(delegate);+ }++ @AfterEach+ public void tearDown() throws IllegalAccessException {+ FieldUtils.writeField(env, "internalCatalogDispatcher", previousCatalogs, true);+ FieldUtils.writeField(env, "internalSchemaDispatcher", previousSchemas, true);+ FieldUtils.writeField(env, "internalTableDispatcher", previousTables, true);+ }++ @Test+ public void testTransferRewritesTheOwnerPropertyOfAnIcebergTable() {+ Table table = mock(Table.class);+ when(table.properties()).thenReturn(ImmutableMap.of("owner", "admin"));+ when(tables.loadTable(TABLE_IDENT)).thenReturn(table);++ dispatcher.setOwner(METALAKE, TABLE, "writer", Owner.Type.USER);++ verify(delegate).setOwner(METALAKE, TABLE, "writer", Owner.Type.USER);+ verify(tables).alterTable(TABLE_IDENT, TableChange.setProperty("owner", "writer"));+ }++ @Test+ public void testTransferRewritesTheOwnerPropertyOfIcebergNamespaces() {+ Schema schema = mock(Schema.class);+ when(schema.properties()).thenReturn(ImmutableMap.of("owner", "admin"));+ when(schemas.loadSchema(SCHEMA_IDENT)).thenReturn(schema);++ dispatcher.setOwners(METALAKE, Collections.singletonList(SCHEMA), "writers", Owner.Type.GROUP);++ verify(schemas).alterSchema(SCHEMA_IDENT, SchemaChange.setProperty("owner", "writers"));+ }++ @Test+ public void testObjectsWithoutThePropertyOrOutsideIcebergAreLeftAlone() {+ Table table = mock(Table.class);+ when(table.properties()).thenReturn(ImmutableMap.of("k", "v"));+ when(tables.loadTable(TABLE_IDENT)).thenReturn(table);+ dispatcher.setOwner(METALAKE, TABLE, "writer", Owner.Type.USER);++ when(catalog.provider()).thenReturn("hive");+ when(table.properties()).thenReturn(ImmutableMap.of("owner", "admin"));+ dispatcher.setOwner(METALAKE, TABLE, "writer", Owner.Type.USER);++ verify(tables, never()).alterTable(any(), any());+ }++ @Test+ public void testAFailedPropertyUpdateDoesNotFailTheTransfer() {+ Table table = mock(Table.class);+ when(table.properties()).thenReturn(ImmutableMap.of("owner", "admin"));+ when(tables.loadTable(TABLE_IDENT)).thenReturn(table);+ when(tables.alterTable(any(), any())).thenThrow(new IllegalStateException("catalog down"));++ Assertions.assertDoesNotThrow(+ () -> dispatcher.setOwner(METALAKE, TABLE, "writer", Owner.Type.USER));+ verify(delegate).setOwner(METALAKE, TABLE, "writer", Owner.Type.USER);+ }++ @Test+ public void testAFailedTransferDoesNotTouchTheProperty() {+ Mockito.doThrow(new IllegalArgumentException("no such user"))+ .when(delegate)+ .setOwner(METALAKE, TABLE, "nobody", Owner.Type.USER);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> dispatcher.setOwner(METALAKE, TABLE, "nobody", Owner.Type.USER));+ verify(tables, never()).loadTable(any());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java b/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.javaindex 88f4bc6404..e00324a60f 100644--- a/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java+++ b/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java@@ -55,4 +55,20 @@ public class TestCatalogCredentialManager {credentialManager.getCredentialProvider(JdbcCredential.JDBC_CREDENTIAL_TYPE).isPresent());}}++ @Test+ void testSupportsPathOnlyWhenAProviderCoversTheScheme() {+ try (CatalogCredentialManager noProviders =+ new CatalogCredentialManager("no-providers", ImmutableMap.of())) {+ Assertions.assertFalse(noProviders.supportsPath("s3://bucket/warehouse/table"));+ }+ try (CatalogCredentialManager storageProvider =+ new CatalogCredentialManager(+ "storage",+ ImmutableMap.of(+ CredentialConstants.CREDENTIAL_PROVIDERS,+ DummyCredentialProvider.CREDENTIAL_TYPE))) {+ Assertions.assertTrue(storageProvider.supportsPath("s3://bucket/warehouse/table"));+ }+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.javaindex c6d44c86d8..8ff9b6de69 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java@@ -30,6 +30,7 @@ import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.stream.Stream;@@ -50,6 +51,7 @@ import org.apache.gravitino.utils.ClassUtils;import org.apache.gravitino.utils.MapUtils;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.BaseTable;+import org.apache.iceberg.DeleteFile;import org.apache.iceberg.FileScanTask;import org.apache.iceberg.IncrementalAppendScan;import org.apache.iceberg.Scan;@@ -61,7 +63,9 @@ import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.exceptions.NoSuchPlanTaskException;+import org.apache.iceberg.exceptions.ServiceFailureException;import org.apache.iceberg.exceptions.ServiceUnavailableException;+import org.apache.iceberg.exceptions.ValidationException;import org.apache.iceberg.io.CloseableIterable;import org.apache.iceberg.rest.CatalogHandlers;import org.apache.iceberg.rest.PlanStatus;@@ -385,7 +389,27 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {}validateCredentialLocation(loadTableResponse.tableMetadata().location());- return !isLocalOrHdfsTable(loadTableResponse.tableMetadata());+ return canVendCredentials(loadTableResponse.tableMetadata().location());+ }++ /**+ * Whether this catalog can vend credentials for a location. The access-delegation header only+ * tells the server what the client supports, and the server may supply none of the mechanisms, so+ * a location no configured provider covers is served without credentials instead of failing the+ * request.+ */+ private boolean canVendCredentials(String location) {+ if (isLocalOrHdfsLocation(location)) {+ return false;+ }+ if (!catalogCredentialManager.supportsPath(location)) {+ LOG.debug(+ "No credential provider of catalog {} covers {}, serving without vended credentials",+ catalogCredentialManager.catalogName(),+ location);+ return false;+ }+ return true;}private boolean isLocalOrHdfsTable(TableMetadata tableMetadata) {@@ -503,6 +527,7 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {tableIdentifier);}+ checkDeleteFilesCanBeReferenced(tableIdentifier, fileScanTasks);try {response = buildCompletedPlanTableScanResponse(table, fileScanTasks);} catch (Exception e) {@@ -517,14 +542,17 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {scanPlanCache.put(ScanPlanCacheKey.create(tableIdentifier, table, scanRequest), response);}- if (requestCredentialVending && !isLocalOrHdfsLocation(table.location())) {+ if (requestCredentialVending && canVendCredentials(table.location())) {response = injectScanCredentials(tableIdentifier, table, response, privilege);}return response;- } catch (IllegalArgumentException e) {- LOG.error("Invalid scan request for table {}: {}", tableIdentifier, e.getMessage());- throw new IllegalArgumentException("Invalid scan parameters: " + e.getMessage(), e);+ } catch (IllegalArgumentException | ValidationException e) {+ // A filter is bound to the schema only while files are planned, so an unknown column or a+ // value of the wrong type surfaces here as a ValidationException.+ LOG.info("Invalid scan request for table {}: {}", tableIdentifier, e.getMessage());+ throw new IllegalArgumentException(+ "Invalid scan parameters: " + withoutSchemaStruct(e.getMessage()), e);} catch (org.apache.iceberg.exceptions.NoSuchTableException e) {LOG.error("Table not found during scan planning: {}", tableIdentifier);throw e;@@ -629,6 +657,10 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {Long startSnapshotId = scanRequest.startSnapshotId();Long endSnapshotId = scanRequest.endSnapshotId();// Use IncrementalAppendScan if both start and end snapshot IDs are provided+ if (startSnapshotId != null && startSnapshotId.equals(endSnapshotId)) {+ // The start is exclusive, so the range from a snapshot to itself is empty.+ return CloseableIterable.empty();+ }if (startSnapshotId != null && endSnapshotId != null) {LOG.debug("Using IncrementalAppendScan for table: {}, from snapshot: {} to snapshot: {}",@@ -638,7 +670,9 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {IncrementalAppendScan incrementalScan =table.newIncrementalAppendScan()- .fromSnapshotInclusive(startSnapshotId)+ // The REST spec defines start-snapshot-id as exclusive, and Iceberg's REST client+ // sends it from appendsBetween/appendsAfter, which are exclusive as well.+ .fromSnapshotExclusive(startSnapshotId).toSnapshot(endSnapshotId);incrementalScan = applyScanRequest(incrementalScan, scanRequest);return incrementalScan.planFiles();@@ -696,6 +730,15 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {@SuppressWarnings("unchecked")private <T extends Scan> T applyScanStatsFields(T scan, PlanTableScanRequest scanRequest) {if (scanRequest.statsFields() != null && !scanRequest.statsFields().isEmpty()) {+ for (String field : scanRequest.statsFields()) {+ boolean known =+ scanRequest.caseSensitive()+ ? scan.schema().findField(field) != null+ : scan.schema().caseInsensitiveFindField(field) != null;+ if (!known) {+ throw new IllegalArgumentException("Invalid statistics fields: unknown field " + field);+ }+ }try {scan = (T) scan.includeColumnStats(scanRequest.statsFields());LOG.debug("Applied statistics fields: {}", scanRequest.statsFields());@@ -777,4 +820,35 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {identifier, currentUuid, request.metadataLocation(), newUuid);}}++ /**+ * Iceberg's plan response serializer refers to delete files by their location. Deletion vectors+ * that share one Puffin file have the same location, so every task would refer to whichever of+ * them was indexed last, and a client would apply the wrong deletion vector. Such a plan is+ * refused rather than answered wrongly.+ */+ @VisibleForTesting+ static void checkDeleteFilesCanBeReferenced(+ TableIdentifier tableIdentifier, List<FileScanTask> fileScanTasks) {+ Map<String, DeleteFile> byLocation = new HashMap<>();+ for (FileScanTask task : fileScanTasks) {+ for (DeleteFile deleteFile : task.deletes()) {+ DeleteFile other = byLocation.putIfAbsent(deleteFile.location(), deleteFile);+ if (other != null+ && !(Objects.equals(other.contentOffset(), deleteFile.contentOffset())+ && Objects.equals(other.referencedDataFile(), deleteFile.referencedDataFile()))) {+ throw new ServiceFailureException(+ "Server-side scan planning cannot return table %s: several deletion vectors are"+ + " stored in %s, which the plan response format cannot reference separately;"+ + " plan the scan on the client",+ tableIdentifier, deleteFile.location());+ }+ }+ }+ }++ private static String withoutSchemaStruct(String message) {+ // Iceberg's binding errors append the whole table struct; it is not useful to a client.+ return message == null ? null : message.replaceAll(" in struct: .*$", "");+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergObjectMapper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergObjectMapper.javaindex 1fe00b2eff..c4a52aaaad 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergObjectMapper.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergObjectMapper.java@@ -28,11 +28,14 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.PropertyNamingStrategies;import com.fasterxml.jackson.databind.module.SimpleModule;+import com.fasterxml.jackson.databind.node.BooleanNode;import com.fasterxml.jackson.databind.node.ObjectNode;import java.io.IOException;import org.apache.iceberg.PartitionSpecParser;import org.apache.iceberg.UnboundPartitionSpec;import org.apache.iceberg.rest.RESTSerializers;+import org.apache.iceberg.rest.requests.PlanTableScanRequest;+import org.apache.iceberg.rest.requests.PlanTableScanRequestParser;import org.apache.iceberg.rest.requests.UpdateTableRequest;import org.apache.iceberg.rest.requests.UpdateTableRequestParser;@@ -53,6 +56,7 @@ public class IcebergObjectMapper {SimpleModule module = new SimpleModule("gravitino-iceberg-rest");module.addDeserializer(UnboundPartitionSpec.class, new PartitionSpecDeserializer());module.addDeserializer(UpdateTableRequest.class, new UpdateTableRequestDeserializer());+ module.addDeserializer(PlanTableScanRequest.class, new PlanTableScanRequestDeserializer());mapper.registerModule(module);return mapper;}@@ -95,6 +99,45 @@ public class IcebergObjectMapper {}}+ /**+ * The REST spec writes the constant expressions as {@code {"type": "true"}} and {@code {"type":+ * "false"}}, while Iceberg's parser accepts them only as JSON booleans. Both forms are accepted.+ */+ private static class PlanTableScanRequestDeserializer+ extends JsonDeserializer<PlanTableScanRequest> {+ @Override+ public PlanTableScanRequest deserialize(JsonParser parser, DeserializationContext context)+ throws IOException {+ JsonNode node = parser.getCodec().readTree(parser);+ if (node instanceof ObjectNode && node.has("filter")) {+ ((ObjectNode) node).set("filter", normalizeConstants(node.get("filter")));+ }+ return PlanTableScanRequestParser.fromJson(node);+ }++ private static JsonNode normalizeConstants(JsonNode expression) {+ if (!(expression instanceof ObjectNode)) {+ return expression;+ }+ ObjectNode object = (ObjectNode) expression;+ JsonNode type = object.get("type");+ if (type != null && type.isTextual() && object.size() == 1) {+ if ("true".equals(type.asText())) {+ return BooleanNode.TRUE;+ }+ if ("false".equals(type.asText())) {+ return BooleanNode.FALSE;+ }+ }+ for (String child : new String[] {"left", "right", "child"}) {+ if (object.has(child)) {+ object.set(child, normalizeConstants(object.get(child)));+ }+ }+ return object;+ }+ }+public static ObjectMapper getInstance() {return objectMapper;}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.javanew file mode 100644index 0000000000..76a668c9e6--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.java@@ -0,0 +1,146 @@+/*+ * 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.iceberg.service.dispatcher;++import com.google.common.annotations.VisibleForTesting;+import java.time.Instant;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.meta.ViewEntity;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Records who created an object through the Iceberg REST catalog. The Iceberg catalog reports no+ * creator or create time, so an object imported into Gravitino after an IRC create would otherwise+ * have an empty audit.+ */+final class IcebergEntityAuditUtils {++ private static final Logger LOG = LoggerFactory.getLogger(IcebergEntityAuditUtils.class);++ private IcebergEntityAuditUtils() {}++ /**+ * Sets the creator and create time of an imported schema, table or view whose stored audit has no+ * creator. A creator the catalog already reported is kept. The object already exists when this is+ * called, so a failure to record the audit is logged rather than failing the request.+ *+ * @param identifier the Gravitino identifier of the object+ * @param type {@link Entity.EntityType#SCHEMA}, {@link Entity.EntityType#TABLE} or {@link+ * Entity.EntityType#VIEW}+ * @param user the authenticated user who created the object+ */+ static void recordCreator(NameIdentifier identifier, Entity.EntityType type, String user) {+ EntityStore store = GravitinoEnv.getInstance().entityStore();+ if (store == null) {+ return;+ }+ Instant createTime = Instant.now();+ try {+ switch (type) {+ case SCHEMA:+ store.update(+ identifier,+ SchemaEntity.class,+ type,+ schema -> withCreator(schema, withCreator(schema.auditInfo(), user, createTime)));+ break;+ case TABLE:+ store.update(+ identifier,+ TableEntity.class,+ type,+ table -> withCreator(table, withCreator(table.auditInfo(), user, createTime)));+ break;+ case VIEW:+ store.update(+ identifier,+ ViewEntity.class,+ type,+ view -> withCreator(view, withCreator(view.auditInfo(), user, createTime)));+ break;+ default:+ throw new IllegalArgumentException("Unsupported entity type: " + type);+ }+ } catch (Exception e) {+ LOG.warn("Failed to record the creator of {} {} created by {}", type, identifier, user, e);+ }+ }++ @VisibleForTesting+ static AuditInfo withCreator(AuditInfo audit, String user, Instant createTime) {+ if (audit != null && audit.creator() != null) {+ return audit;+ }+ return AuditInfo.builder()+ .withCreator(user)+ .withCreateTime(createTime)+ .withLastModifier(audit == null ? null : audit.lastModifier())+ .withLastModifiedTime(audit == null ? null : audit.lastModifiedTime())+ .build();+ }++ private static SchemaEntity withCreator(SchemaEntity schema, AuditInfo audit) {+ return SchemaEntity.builder()+ .withId(schema.id())+ .withName(schema.name())+ .withNamespace(schema.namespace())+ .withComment(schema.comment())+ .withProperties(schema.properties())+ .withAuditInfo(audit)+ .build();+ }++ private static TableEntity withCreator(TableEntity table, AuditInfo audit) {+ return TableEntity.builder()+ .withId(table.id())+ .withName(table.name())+ .withNamespace(table.namespace())+ .withComment(table.comment())+ .withProperties(table.properties())+ .withColumns(table.columns())+ .withPartitioning(table.partitioning())+ .withDistribution(table.distribution())+ .withSortOrders(table.sortOrders())+ .withIndexes(table.indexes())+ .withAuditInfo(audit)+ .build();+ }++ private static ViewEntity withCreator(ViewEntity view, AuditInfo audit) {+ return ViewEntity.builder()+ .withId(view.id())+ .withName(view.name())+ .withNamespace(view.namespace())+ .withComment(view.comment())+ .withColumns(view.columns())+ .withRepresentations(view.representations())+ .withDefaultCatalog(view.defaultCatalog())+ .withDefaultSchema(view.defaultSchema())+ .withProperties(view.properties())+ .withAuditInfo(audit)+ .build();+ }+}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 1759c2e1fb..8394307c8b 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@@ -97,6 +97,13 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation// 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);+ for (Namespace created : newlyOwned) {+ IcebergEntityAuditUtils.recordCreator(+ IcebergIdentifierUtils.toGravitinoSchemaIdentifier(+ metalake, catalogName, created, HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.SCHEMA,+ context.userName());+ }IcebergOwnershipUtils.setSchemaOwners(metalake,catalogName,@@ -231,6 +238,14 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation// 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.importTable(context.catalogName(), namespace, registerTableRequest.name());+ IcebergEntityAuditUtils.recordCreator(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, registerTableRequest.name()),+ HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.TABLE,+ context.userName());IcebergOwnershipUtils.setTableOwner(metalake,@@ -258,6 +273,14 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation// 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.importView(context.catalogName(), namespace, registerViewRequest.name());+ IcebergEntityAuditUtils.recordCreator(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, registerViewRequest.name()),+ HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.VIEW,+ context.userName());IcebergOwnershipUtils.setViewOwner(metalake,diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.javaindex a884685c92..18aa2326d3 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java@@ -19,19 +19,26 @@package org.apache.gravitino.iceberg.service.dispatcher;+import com.google.common.annotations.VisibleForTesting;import java.util.HashMap;import java.util.Map;import java.util.Optional;+import java.util.Set;+import java.util.TreeSet;+import java.util.stream.Collectors;import org.apache.gravitino.Entity;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;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.cleanup.IcebergCleanupManager;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.TableMetadata;import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;import org.apache.iceberg.rest.requests.RegisterTableRequest;import org.apache.iceberg.rest.requests.RegisterViewRequest;@@ -63,6 +70,7 @@ public class IcebergNamespaceOperationExecutor implements IcebergNamespaceOperat@Overridepublic CreateNamespaceResponse createNamespace(IcebergRequestContext context, CreateNamespaceRequest createNamespaceRequest) {+ checkLevelsDoNotContainSchemaSeparator(createNamespaceRequest.namespace());String authenticatedUser = context.userName();if (!AuthConstants.ANONYMOUS_USER.equals(authenticatedUser)) {String existingOwner = createNamespaceRequest.properties().get(IcebergConstants.OWNER);@@ -95,9 +103,13 @@ public class IcebergNamespaceOperationExecutor implements IcebergNamespaceOperatIcebergRequestContext context,Namespace namespace,UpdateNamespacePropertiesRequest updateNamespacePropertiesRequest) {+ validatePropertyUpdate(updateNamespacePropertiesRequest);return icebergCatalogWrapperManager.getCatalogWrapper(context.catalogName())- .updateNamespaceProperties(namespace, updateNamespacePropertiesRequest);+ .updateNamespaceProperties(+ namespace,+ IcebergOwnerPropertyGuard.protect(+ updateNamespacePropertiesRequest, context.userName()));}@Override@@ -152,4 +164,58 @@ public class IcebergNamespaceOperationExecutor implements IcebergNamespaceOperat.getCatalogWrapper(context.catalogName()).registerView(namespace, registerViewRequest);}++ /**+ * With authorization enabled, a namespace is governed as the Gravitino schema named by its levels+ * joined with the schema separator. A level that contains the separator would give two different+ * namespaces, such as {@code ["a:b"]} and {@code ["a", "b"]}, the same schema, and so the same+ * owner and privileges: whoever creates one would take over the other. Such a level is refused+ * before anything is created.+ */+ @VisibleForTesting+ static void checkLevelsDoNotContainSchemaSeparator(Namespace namespace) {+ if (namespace == null || !isAuthorizationEnabled()) {+ return;+ }+ String separator = HierarchicalSchemaUtil.schemaSeparator();+ for (String level : namespace.levels()) {+ if (level.contains(separator)) {+ throw new BadRequestException(+ "Invalid namespace %s: the level '%s' contains '%s', which separates the levels of a"+ + " nested namespace",+ namespace, level, separator);+ }+ }+ }++ /**+ * Rejects a property update that sets a null value or removes a null key. Iceberg's request+ * builder refuses these, but a request read from JSON skips the builder, and the JDBC catalog+ * would store a null value that makes the namespace unreadable.+ */+ @VisibleForTesting+ static void validatePropertyUpdate(UpdateNamespacePropertiesRequest request) {+ Set<String> nullValues =+ request.updates().entrySet().stream()+ .filter(entry -> entry.getKey() == null || entry.getValue() == null)+ .map(entry -> String.valueOf(entry.getKey()))+ .collect(Collectors.toCollection(TreeSet::new));+ if (!nullValues.isEmpty()) {+ throw new IllegalArgumentException(+ String.format(+ "Invalid value to update for properties %s: null. Use remove instead", nullValues));+ }+ if (request.removals().contains(null)) {+ throw new IllegalArgumentException("Invalid property to remove: null");+ }+ }++ private static boolean isAuthorizationEnabled() {+ try {+ return IcebergRESTServerContext.getInstance().isAuthorizationEnabled();+ } catch (IllegalStateException e) {+ // The server context is not initialized, as in a standalone executor.+ return false;+ }+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnerPropertyGuard.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnerPropertyGuard.javanew file mode 100644index 0000000000..6085cacdd2--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergOwnerPropertyGuard.java@@ -0,0 +1,132 @@+/*+ * 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.iceberg.service.dispatcher;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;+import org.apache.iceberg.MetadataUpdate;+import org.apache.iceberg.UpdateRequirement;+import org.apache.iceberg.rest.requests.UpdateNamespacePropertiesRequest;+import org.apache.iceberg.rest.requests.UpdateTableRequest;++/**+ * Keeps the {@code owner} property of namespaces and tables under Gravitino's control. The Iceberg+ * REST catalog sets it to the creator, and an ownership transfer in Gravitino rewrites it; a+ * property update through the Iceberg REST catalog cannot change it.+ *+ * <p>Updates to the property are dropped rather than rejected: engines send it on their own, for+ * example Spark adds the current user as {@code owner} when it creates or replaces a table, and+ * rejecting it would fail those statements.+ */+final class IcebergOwnerPropertyGuard {++ private IcebergOwnerPropertyGuard() {}++ /**+ * Returns the request without changes to the owner property. A commit that creates the table sets+ * the property to the authenticated user instead, as a direct create does.+ *+ * @param request the table commit+ * @param user the authenticated user+ * @return the request to apply+ */+ static UpdateTableRequest protect(UpdateTableRequest request, String user) {+ if (AuthConstants.ANONYMOUS_USER.equals(user) || !touchesOwner(request)) {+ return request;+ }+ boolean creates =+ request.requirements().stream()+ .anyMatch(UpdateRequirement.AssertTableDoesNotExist.class::isInstance);+ List<MetadataUpdate> updates = new ArrayList<>();+ for (MetadataUpdate update : request.updates()) {+ if (update instanceof MetadataUpdate.SetProperties) {+ Map<String, String> properties =+ new HashMap<>(((MetadataUpdate.SetProperties) update).updated());+ if (creates) {+ properties.put(IcebergConstants.OWNER, user);+ } else {+ properties.remove(IcebergConstants.OWNER);+ }+ if (!properties.isEmpty()) {+ updates.add(new MetadataUpdate.SetProperties(properties));+ }+ } else if (update instanceof MetadataUpdate.RemoveProperties) {+ List<String> removed =+ ((MetadataUpdate.RemoveProperties) update)+ .removed().stream()+ .filter(key -> !IcebergConstants.OWNER.equals(key))+ .collect(Collectors.toList());+ if (!removed.isEmpty()) {+ updates.add(new MetadataUpdate.RemoveProperties(new HashSet<>(removed)));+ }+ } else {+ updates.add(update);+ }+ }+ return request.identifier() == null+ ? new UpdateTableRequest(request.requirements(), updates)+ : UpdateTableRequest.create(request.identifier(), request.requirements(), updates);+ }++ /**+ * Returns the request without changes to the owner property.+ *+ * @param request the namespace property update+ * @param user the authenticated user+ * @return the request to apply+ */+ static UpdateNamespacePropertiesRequest protect(+ UpdateNamespacePropertiesRequest request, String user) {+ if (AuthConstants.ANONYMOUS_USER.equals(user)+ || (!request.updates().containsKey(IcebergConstants.OWNER)+ && !request.removals().contains(IcebergConstants.OWNER))) {+ return request;+ }+ Map<String, String> updates = new HashMap<>(request.updates());+ updates.remove(IcebergConstants.OWNER);+ List<String> removals =+ request.removals().stream()+ .filter(key -> !IcebergConstants.OWNER.equals(key))+ .collect(Collectors.toList());+ return UpdateNamespacePropertiesRequest.builder()+ .updateAll(updates)+ .removeAll(removals)+ .build();+ }++ private static boolean touchesOwner(UpdateTableRequest request) {+ return request.updates().stream()+ .anyMatch(+ update ->+ (update instanceof MetadataUpdate.SetProperties+ && ((MetadataUpdate.SetProperties) update)+ .updated()+ .containsKey(IcebergConstants.OWNER))+ || (update instanceof MetadataUpdate.RemoveProperties+ && ((MetadataUpdate.RemoveProperties) update)+ .removed()+ .contains(IcebergConstants.OWNER)));+ }+}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableEventDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableEventDispatcher.javaindex dc05033e59..d9aa0fe73d 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableEventDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableEventDispatcher.java@@ -50,6 +50,9 @@ import org.apache.gravitino.listener.api.event.IcebergPlanTableScanPreEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTableEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTableFailureEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTablePreEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsFailureEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsPreEvent;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.listener.api.event.IcebergTableExistsEvent;import org.apache.gravitino.listener.api.event.IcebergTableExistsFailureEvent;@@ -60,6 +63,7 @@ import org.apache.gravitino.listener.api.event.IcebergUpdateTablePreEvent;import org.apache.gravitino.utils.RequestContext;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.metrics.MetricsReport;import org.apache.iceberg.rest.requests.CreateTableRequest;import org.apache.iceberg.rest.requests.FetchScanTasksRequest;import org.apache.iceberg.rest.requests.PlanTableScanRequest;@@ -244,6 +248,25 @@ public class IcebergTableEventDispatcher implements IcebergTableOperationDispatcreturn isExists;}+ @Override+ public void checkTableMetricsReport(+ IcebergRequestContext context, TableIdentifier tableIdentifier, MetricsReport report) {+ NameIdentifier gravitinoNameIdentifier =+ IcebergRESTUtils.getGravitinoNameIdentifier(+ metalakeName, context.catalogName(), tableIdentifier);+ eventBus.dispatchEvent(new IcebergReportTableMetricsPreEvent(context, gravitinoNameIdentifier));+ try {+ // The delegate checks existence without a table-exists event of its own: the client+ // reported metrics, it did not ask whether the table exists.+ icebergTableOperationDispatcher.checkTableMetricsReport(context, tableIdentifier, report);+ } catch (Exception e) {+ eventBus.dispatchEvent(+ new IcebergReportTableMetricsFailureEvent(context, gravitinoNameIdentifier, e));+ throw e;+ }+ eventBus.dispatchEvent(new IcebergReportTableMetricsEvent(context, gravitinoNameIdentifier));+ }+@Overridepublic void renameTable(IcebergRequestContext context, RenameTableRequest renameTableRequest) {TableIdentifier sourceTable = renameTableRequest.source();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 c6578af0c4..7e5c39c066 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@@ -18,6 +18,7 @@*/package org.apache.gravitino.iceberg.service.dispatcher;+import com.google.common.annotations.VisibleForTesting;import java.io.IOException;import java.time.Instant;import java.util.Optional;@@ -36,6 +37,7 @@ 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.MetadataUpdate;import org.apache.iceberg.UpdateRequirement;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;@@ -108,6 +110,11 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatch: dispatcher.updateTable(context, tableIdentifier, updateTableRequest);if (isStagedCreateCommit) {importTableAndSetOwner(context, tableIdentifier.namespace(), tableIdentifier.name());+ } else if (changesSchema(updateTableRequest)) {+ // Bring the stored columns up to date now, while the request runs as the committing user, so+ // the change is recorded as theirs. Left to the next load, it is recorded as whoever loads+ // the table first, or as anonymous when that is a background listener.+ importTableEntity(context.catalogName(), tableIdentifier.namespace(), tableIdentifier.name());}return response;}@@ -236,11 +243,28 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatchreturn dispatcher.getTableMetadataLocation(context, tableIdentifier);}+ @VisibleForTesting+ static boolean changesSchema(UpdateTableRequest updateTableRequest) {+ return updateTableRequest.updates().stream()+ .anyMatch(+ update ->+ update instanceof MetadataUpdate.AddSchema+ || update instanceof MetadataUpdate.SetCurrentSchema);+ }+private void importTableAndSetOwner(IcebergRequestContext context, Namespace namespace, String tableName) {// Validate request metadata before the backend operation. An unexpected import failure must// propagate without deleting a table that another client may already have updated or recreated.importTableEntity(context.catalogName(), namespace, tableName);+ IcebergEntityAuditUtils.recordCreator(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, tableName),+ HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.TABLE,+ context.userName());IcebergOwnershipUtils.setTableOwner(metalake,context.catalogName(),diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationDispatcher.javaindex c05173621a..7242ff7965 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableOperationDispatcher.java@@ -23,6 +23,10 @@ import java.util.Optional;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.NoSuchTableException;+import org.apache.iceberg.metrics.CommitReport;+import org.apache.iceberg.metrics.MetricsReport;+import org.apache.iceberg.metrics.ScanReport;import org.apache.iceberg.rest.requests.CreateTableRequest;import org.apache.iceberg.rest.requests.FetchScanTasksRequest;import org.apache.iceberg.rest.requests.PlanTableScanRequest;@@ -101,6 +105,41 @@ public interface IcebergTableOperationDispatcher {*/boolean tableExists(IcebergRequestContext context, TableIdentifier tableIdentifier);+ /**+ * Checks that a metrics report can be recorded for an Iceberg table: the table must exist and the+ * report must name it.+ *+ * @param context Iceberg REST request context information.+ * @param tableIdentifier The Iceberg table identifier from the request path.+ * @param report The metrics report sent by the client.+ * @throws NoSuchTableException if the table does not exist.+ * @throws IllegalArgumentException if the report is of an unsupported type or names another+ * table.+ */+ default void checkTableMetricsReport(+ IcebergRequestContext context, TableIdentifier tableIdentifier, MetricsReport report) {+ if (!tableExists(context, tableIdentifier)) {+ throw new NoSuchTableException("Table %s not found", tableIdentifier);+ }+ String reportedTableName;+ if (report instanceof CommitReport) {+ reportedTableName = ((CommitReport) report).tableName();+ } else if (report instanceof ScanReport) {+ reportedTableName = ((ScanReport) report).tableName();+ } else {+ throw new IllegalArgumentException("Unsupported metrics report type");+ }+ String tableName = tableIdentifier.name();+ String qualifiedTableName = tableIdentifier.toString();+ if (reportedTableName == null+ || (!tableName.equals(reportedTableName)+ && !qualifiedTableName.equals(reportedTableName)+ && !reportedTableName.endsWith("." + qualifiedTableName))) {+ throw new IllegalArgumentException(+ "Metrics report table name does not match the requested table");+ }+ }+/*** Rename an Iceberg table.*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 c935f6d700..fac0cf4af1 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@@ -126,7 +126,9 @@ public class IcebergTableOperationExecutor implements IcebergTableOperationDispaIcebergColumnFieldValidator.validateUpdate(updateTableRequest);return icebergCatalogWrapperManager.getCatalogWrapper(context.catalogName())- .updateTable(tableIdentifier, updateTableRequest);+ .updateTable(+ tableIdentifier,+ IcebergOwnerPropertyGuard.protect(updateTableRequest, context.userName()));}@Overridediff --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 bce140877b..650276d8eb 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@@ -73,6 +73,14 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcher// Then import it into Gravitino so Gravitino is aware of the viewimportView(context.catalogName(), namespace, createViewRequest.name());+ IcebergEntityAuditUtils.recordCreator(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, createViewRequest.name()),+ HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.VIEW,+ context.userName());// Set ownership for the newly created view.IcebergOwnershipUtils.setViewOwner(diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.javaindex 59e0f9fdde..d115fd175b 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java@@ -38,11 +38,15 @@ import javax.ws.rs.core.Context;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;+import org.apache.gravitino.Entity;+import org.apache.gravitino.MetadataObject;import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;import org.apache.gravitino.iceberg.service.IcebergRESTUtils;import org.apache.gravitino.metrics.MetricNames;+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;+import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.iceberg.rest.Endpoint;import org.apache.iceberg.rest.responses.ConfigResponse;@@ -101,7 +105,14 @@ public class IcebergConfigOperations {@Produces(MediaType.APPLICATION_JSON)@Timed(name = "config." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "config", absolute = true)- public Response getConfig(@DefaultValue("") @QueryParam("warehouse") String warehouse) {+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_CATALOG_AUTHORIZATION_EXPRESSION,+ accessMetadataType = MetadataObject.Type.CATALOG)+ public Response getConfig(+ @AuthorizationMetadata(type = Entity.EntityType.CATALOG)+ @DefaultValue("")+ @QueryParam("warehouse")+ String warehouse) {String catalogName = getCatalogName(warehouse);CatalogWrapperForREST catalogWrapper = getCatalogWrapper(catalogName);boolean supportsView = catalogWrapper.supportsViewOperations();@@ -137,7 +148,9 @@ public class IcebergConfigOperations {private String getCatalogName(String warehouse) {if (StringUtils.isBlank(warehouse)) {- return IcebergConstants.ICEBERG_REST_DEFAULT_CATALOG;+ // The same default catalog an empty prefix resolves to, and that the request is authorized+ // against.+ return IcebergRESTUtils.getCatalogName(warehouse);} else {return warehouse;}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 f62c6048cc..4773a3e995 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@@ -23,10 +23,9 @@ import com.codahale.metrics.annotation.Timed;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.google.common.annotations.VisibleForTesting;-import java.util.ArrayList;+import java.util.Arrays;import java.util.List;import java.util.Optional;-import java.util.regex.Pattern;import javax.inject.Inject;import javax.servlet.http.HttpServletRequest;import javax.ws.rs.Consumes;@@ -391,37 +390,34 @@ 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);- // 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;- }-- private ListNamespacesResponse filterListNamespacesResponse(+ /**+ * Keeps the namespaces the caller may see, as the catalog listed them.+ *+ * @param listNamespacesResponse the namespaces the catalog returned+ * @param metalake the metalake of the catalog+ * @param catalogName the catalog+ * @return the namespaces the caller may see+ */+ @VisibleForTesting+ static ListNamespacesResponse filterListNamespacesResponse(ListNamespacesResponse listNamespacesResponse, String metalake, String catalogName) {String separator = HierarchicalSchemaUtil.schemaSeparator();- NameIdentifier[] idents =+ Namespace[] namespaces =+ listNamespacesResponse.namespaces().stream()+ .filter(namespace -> !namespace.isEmpty())+ .toArray(Namespace[]::new);+ // Filter the namespaces as the catalog listed them. Rebuilding them from the Gravitino schema+ // name would split a level that contains the separator into several levels.+ Namespace[] filtered =MetadataAuthzHelper.filterByExpression(metalake,AuthorizationExpressionConstants.FILTER_SCHEMA_AUTHORIZATION_EXPRESSION,Entity.EntityType.SCHEMA,- toNameIdentifiers(listNamespacesResponse, metalake, catalogName));- List<Namespace> filteredNamespaces = new ArrayList<>();- for (NameIdentifier ident : idents) {- if (ident.hasNamespace() && ident.namespace().levels().length >= 2) {- // 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)));- }- }+ namespaces,+ namespace ->+ NameIdentifier.of(+ metalake, catalogName, String.join(separator, namespace.levels())));+ List<Namespace> filteredNamespaces = Arrays.asList(filtered);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 e098f2ef57..21b2245c05 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@@ -78,10 +78,7 @@ import org.apache.iceberg.SnapshotRef;import org.apache.iceberg.TableMetadata;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;-import org.apache.iceberg.exceptions.NoSuchTableException;-import org.apache.iceberg.metrics.CommitReport;import org.apache.iceberg.metrics.MetricsReport;-import org.apache.iceberg.metrics.ScanReport;import org.apache.iceberg.rest.RESTUtil;import org.apache.iceberg.rest.requests.CreateTableRequest;import org.apache.iceberg.rest.requests.FetchScanTasksRequest;@@ -449,26 +446,8 @@ public class IcebergTableOperations {IcebergRequestContext context =new IcebergRequestContext(httpServletRequest(), catalogName);TableIdentifier tableIdentifier = TableIdentifier.of(icebergNS, tableName);- if (!tableOperationDispatcher.tableExists(context, tableIdentifier)) {- throw new NoSuchTableException("Table %s not found", tableIdentifier);- }MetricsReport report = request.report();- String reportedTableName;- if (report instanceof CommitReport) {- reportedTableName = ((CommitReport) report).tableName();- } else if (report instanceof ScanReport) {- reportedTableName = ((ScanReport) report).tableName();- } else {- throw new IllegalArgumentException("Unsupported metrics report type");- }- String qualifiedTableName = tableIdentifier.toString();- if (reportedTableName == null- || (!tableName.equals(reportedTableName)- && !qualifiedTableName.equals(reportedTableName)- && !reportedTableName.endsWith("." + qualifiedTableName))) {- throw new IllegalArgumentException(- "Metrics report table name does not match the requested table");- }+ tableOperationDispatcher.checkTableMetricsReport(context, tableIdentifier, report);boolean accepted = icebergMetricsManager.recordMetric(catalogName, icebergNS, report);if (accepted) {return IcebergRESTUtils.noContent();@@ -759,25 +738,21 @@ public class IcebergTableOperations {* requesting credential vending. Package-private and static so that {@link* IcebergNamespaceOperations#registerTable} can reuse the same parsing logic from the same* package.+ *+ * <p>The header is a comma-separated list of the mechanisms the client supports, and the server+ * may serve the request with any or none of them, so mechanisms this server does not offer (such+ * as remote-signing) are ignored.*/static boolean isCredentialVending(String accessDelegation) {if (StringUtils.isBlank(accessDelegation)) {return false;}- if ("vended-credentials".equalsIgnoreCase(accessDelegation)) {- return true;- }- if ("remote-signing".equalsIgnoreCase(accessDelegation)) {- throw new UnsupportedOperationException(- "Gravitino IcebergRESTServer doesn't support remote signing");- } else {- throw new IllegalArgumentException(- X_ICEBERG_ACCESS_DELEGATION- + ": "- + accessDelegation- + " is illegal, Iceberg REST spec supports: [vended-credentials,remote-signing], "- + "Gravitino Iceberg REST server supports: vended-credentials");+ for (String mechanism : accessDelegation.split(",")) {+ if ("vended-credentials".equalsIgnoreCase(mechanism.trim())) {+ return true;+ }}+ return false;}private NameIdentifier[] toNameIdentifiers(diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsEvent.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsEvent.javanew file mode 100644index 0000000000..2b297011a8--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsEvent.java@@ -0,0 +1,43 @@+/*+ * 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.listener.api.event;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.annotation.DeveloperApi;++/** Represents an event after an Iceberg table metrics report is accepted for a table. */+@DeveloperApi+public class IcebergReportTableMetricsEvent extends IcebergTableEvent {++ /**+ * Creates the event.+ *+ * @param icebergRequestContext the Iceberg REST request context+ * @param tableIdentifier the Gravitino identifier of the table the report is for+ */+ public IcebergReportTableMetricsEvent(+ IcebergRequestContext icebergRequestContext, NameIdentifier tableIdentifier) {+ super(icebergRequestContext, tableIdentifier);+ }++ @Override+ public OperationType operationType() {+ return OperationType.REPORT_TABLE_METRICS;+ }+}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsFailureEvent.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsFailureEvent.javanew file mode 100644index 0000000000..6e9396df03--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsFailureEvent.java@@ -0,0 +1,44 @@+/*+ * 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.listener.api.event;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.annotation.DeveloperApi;++/** Represents a failure event when an Iceberg table metrics report is rejected. */+@DeveloperApi+public class IcebergReportTableMetricsFailureEvent extends IcebergTableFailureEvent {++ /**+ * Creates the event.+ *+ * @param icebergRequestContext the Iceberg REST request context+ * @param tableIdentifier the Gravitino identifier of the table the report is for+ * @param e the reason the report was rejected+ */+ public IcebergReportTableMetricsFailureEvent(+ IcebergRequestContext icebergRequestContext, NameIdentifier tableIdentifier, Exception e) {+ super(icebergRequestContext, tableIdentifier, e);+ }++ @Override+ public OperationType operationType() {+ return OperationType.REPORT_TABLE_METRICS;+ }+}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsPreEvent.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsPreEvent.javanew file mode 100644index 0000000000..eb1a12a291--- /dev/null+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/listener/api/event/IcebergReportTableMetricsPreEvent.java@@ -0,0 +1,43 @@+/*+ * 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.listener.api.event;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.annotation.DeveloperApi;++/** Represents a pre event before an Iceberg table metrics report is checked. */+@DeveloperApi+public class IcebergReportTableMetricsPreEvent extends IcebergTablePreEvent {++ /**+ * Creates the event.+ *+ * @param icebergRequestContext the Iceberg REST request context+ * @param tableIdentifier the Gravitino identifier of the table the report is for+ */+ public IcebergReportTableMetricsPreEvent(+ IcebergRequestContext icebergRequestContext, NameIdentifier tableIdentifier) {+ super(icebergRequestContext, tableIdentifier);+ }++ @Override+ public OperationType operationType() {+ return OperationType.REPORT_TABLE_METRICS;+ }+}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergLoadAuthzHandlerHelper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergLoadAuthzHandlerHelper.javaindex fc03d8aa65..df426feb68 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergLoadAuthzHandlerHelper.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergLoadAuthzHandlerHelper.java@@ -111,6 +111,18 @@ final class IcebergLoadAuthzHandlerHelper {return defaultExpression;}+ static boolean isAllowed(Map<EntityType, NameIdentifier> nameIdentifierMap, String expression) {+ return isAllowed(nameIdentifierMap, expression, new AuthorizationRequestContext());+ }++ static boolean isAllowed(+ Map<EntityType, NameIdentifier> nameIdentifierMap,+ String expression,+ AuthorizationRequestContext requestContext) {+ return new AuthorizationExpressionEvaluator(expression)+ .evaluate(nameIdentifierMap, Collections.emptyMap(), requestContext, Optional.empty());+ }+static void authorizeLoadEntity(Map<EntityType, NameIdentifier> nameIdentifierMap,String primaryExpression,@@ -119,21 +131,12 @@ final class IcebergLoadAuthzHandlerHelper {Supplier<RuntimeException> notFoundException,String entityType,NameIdentifier entityId) {- Map<String, Object> emptyPathParams = Collections.emptyMap();AuthorizationRequestContext requestContext = new AuthorizationRequestContext();- Optional<String> emptyEntityType = Optional.empty();-- AuthorizationExpressionEvaluator primaryEvaluator =- new AuthorizationExpressionEvaluator(primaryExpression);- if (primaryEvaluator.evaluate(- nameIdentifierMap, emptyPathParams, requestContext, emptyEntityType)) {+ if (isAllowed(nameIdentifierMap, primaryExpression, requestContext)) {return;}- AuthorizationExpressionEvaluator allowExistenceEvaluator =- new AuthorizationExpressionEvaluator(allowCheckExistenceExpression);- if (allowExistenceEvaluator.evaluate(- nameIdentifierMap, emptyPathParams, requestContext, emptyEntityType)+ if (isAllowed(nameIdentifierMap, allowCheckExistenceExpression, requestContext)&& !exists.getAsBoolean()) {throw notFoundException.get();}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 c6c67f24b5..baeb09901d 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@@ -26,6 +26,7 @@ import java.util.Map;import java.util.Optional;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Entity;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.NameIdentifier;@@ -36,6 +37,7 @@ import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;import org.apache.gravitino.iceberg.service.IcebergRESTUtils;import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;+import org.apache.gravitino.listener.api.event.EventSource;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;@@ -92,7 +94,11 @@ public class IcebergMetadataAuthorizationMethodInterceptorString value = String.valueOf(args[i]);switch (type) {case CATALOG:- catalog = IcebergRESTUtils.getCatalogName(value);+ // A path prefix ends with '/'; the config endpoint's warehouse is a plain catalog name.+ catalog =+ StringUtils.isBlank(value) || value.endsWith("/")+ ? IcebergRESTUtils.getCatalogName(value)+ : value;nameIdentifierMap.put(Entity.EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalakeName, catalog));break;@@ -170,6 +176,11 @@ public class IcebergMetadataAuthorizationMethodInterceptorreturn Optional.empty();}+ @Override+ protected Optional<EventSource> authorizationDenialEventSource() {+ return Optional.of(EventSource.GRAVITINO_ICEBERG_REST_SERVER);+ }+@Overrideprotected boolean isExceptionPropagate(Exception exception) {return exception.getClass().getName().startsWith("org.apache.iceberg.exceptions");@@ -200,7 +211,10 @@ public class IcebergMetadataAuthorizationMethodInterceptorIcebergCatalogWrapper catalogWrapper;try {catalogWrapper = wrapperManager.getCatalogWrapper(catalogId.name());- } catch (NoSuchCatalogException e) {+ } catch (NoSuchCatalogException | IllegalArgumentException e) {+ // A missing catalog, or a catalog that is not an Iceberg catalog, is not a REST backend:+ // authorize the request normally. A caller without access gets 403 whatever the name+ // refers to, and an authorized caller gets the operation's own error.return false;}// When IRC2 is another Gravitino server, IRC1 acts as a proxy and does not performdiff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergRESTAuthInterceptionService.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergRESTAuthInterceptionService.javaindex b7ea32d820..9c2e14de79 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergRESTAuthInterceptionService.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergRESTAuthInterceptionService.java@@ -23,6 +23,7 @@ import com.google.common.collect.ImmutableSet;import java.lang.reflect.Method;import java.util.List;import org.aopalliance.intercept.MethodInterceptor;+import org.apache.gravitino.iceberg.service.rest.IcebergConfigOperations;import org.apache.gravitino.iceberg.service.rest.IcebergNamespaceOperations;import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;import org.apache.gravitino.iceberg.service.rest.IcebergTableRenameOperations;@@ -41,6 +42,7 @@ public class IcebergRESTAuthInterceptionService extends BaseInterceptionServicepublic Filter getDescriptorFilter() {return new ClassListFilter(ImmutableSet.of(+ IcebergConfigOperations.class.getName(),IcebergTableOperations.class.getName(),IcebergTableRenameOperations.class.getName(),IcebergNamespaceOperations.class.getName(),diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadTableAuthzHandler.javaindex fe24ca53cb..ecbb2188ad 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadTableAuthzHandler.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadTableAuthzHandler.java@@ -20,6 +20,7 @@package org.apache.gravitino.server.web.filter;import java.lang.reflect.Parameter;+import java.util.HashMap;import java.util.Map;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.NameIdentifier;@@ -113,17 +114,21 @@ public class LoadTableAuthzHandler implements AuthorizationHandler {* Perform TABLE-level authorization aligned with {@link* org.apache.gravitino.iceberg.service.rest.IcebergTableOperations#loadTable}: evaluate the* primary expression first; if it denies, evaluate {@link- * AuthorizationExpression#allowCheckExistence()} when non-blank. Before primary expression- * evaluation, if the catalog supports views and the identifier resolves to a view, throws {@link- * NoSuchTableException} so clients can fall back to {@code /views/} (see Iceberg REST spec for- * {@code /tables/}).+ * AuthorizationExpression#allowCheckExistence()} when non-blank.+ *+ * <p>If the identifier resolves to a view, a caller who may load the view or check that it exists+ * gets {@link NoSuchTableException}, so clients can fall back to {@code /views/} (see Iceberg+ * REST spec for {@code /tables/}). Anyone else is answered as for a table name that does not+ * exist, so the response does not reveal that a view has that name.*/private void performTableAuthorization(Map<EntityType, NameIdentifier> nameIdentifierMap,IcebergCatalogWrapper catalogWrapper,TableIdentifier tableIdentifier,NameIdentifier tableId) {- if (catalogWrapper.supportsViewOperations() && catalogWrapper.viewExists(tableIdentifier)) {+ boolean isView =+ catalogWrapper.supportsViewOperations() && catalogWrapper.viewExists(tableIdentifier);+ if (isView && maySeeView(nameIdentifierMap, tableId)) {throw new NoSuchTableException("Table %s not found", tableIdentifier.name());}@@ -136,12 +141,25 @@ public class LoadTableAuthzHandler implements AuthorizationHandler {authorizationExpression,AuthorizationExpressionConstants.ICEBERG_TABLE_EXISTS_SECONDARY_AUTHORIZATION_EXPRESSION),- () -> catalogWrapper.tableExists(tableIdentifier),+ () -> !isView && catalogWrapper.tableExists(tableIdentifier),() -> new NoSuchTableException("Table %s not found", tableIdentifier.name()),"table",tableId);}+ private static boolean maySeeView(+ Map<EntityType, NameIdentifier> nameIdentifierMap, NameIdentifier tableId) {+ Map<EntityType, NameIdentifier> viewMap = new HashMap<>(nameIdentifierMap);+ viewMap.remove(EntityType.TABLE);+ viewMap.put(EntityType.VIEW, NameIdentifier.of(tableId.namespace(), tableId.name()));+ return IcebergLoadAuthzHandlerHelper.isAllowed(+ viewMap, AuthorizationExpressionConstants.ICEBERG_LOAD_VIEW_AUTHORIZATION_EXPRESSION)+ || IcebergLoadAuthzHandlerHelper.isAllowed(+ viewMap,+ AuthorizationExpressionConstants+ .ICEBERG_LOAD_VIEW_EXISTENCE_CHECK_AUTHORIZATION_EXPRESSION);+ }+/*** Check if the table is a metadata table. Metadata tables have special names like* `table$snapshots`, `table$files`, etc., and are accessed with longer namespace pathsdiff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.javaindex 632bea9983..bc57dc4ada 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java@@ -450,6 +450,60 @@ public class TestCatalogWrapperForREST {Assertions.assertDoesNotThrow(() -> wrapper.registerTable(namespace, sameTable));}+ @Test+ void testVendsOnlyWhereACredentialProviderCoversTheLocation() {+ Namespace namespace = Namespace.of("db");+ Schema schema = new Schema(Types.NestedField.required(1, "id", Types.IntegerType.get()));+ TableIdentifier table = TableIdentifier.of(namespace, "tbl");++ // No credential provider: a request asking for vended credentials is served without them.+ CatalogWrapperForREST noProvider =+ new CatalogWrapperForREST(+ "no-provider",+ new IcebergConfig(+ ImmutableMap.of(+ IcebergConstants.CATALOG_BACKEND, "memory",+ IcebergConstants.WAREHOUSE, "/tmp/warehouse")));+ ((SupportsNamespaces) noProvider.getCatalog()).createNamespace(namespace);+ noProvider+ .getCatalog()+ .createTable(+ table,+ schema,+ PartitionSpec.unpartitioned(),+ "s3://bucket/wh/db/tbl",+ Collections.emptyMap());+ LoadTableResponse loaded = noProvider.loadTable(table, true, CredentialPrivilege.READ);+ Assertions.assertFalse(noProvider.shouldGenerateCredential(loaded, true));+ Assertions.assertTrue(loaded.credentials().isEmpty());+ Assertions.assertTrue(+ loaded.config().keySet().stream().noneMatch(key -> key.startsWith("s3.")),+ loaded.config().toString());++ // With a provider covering the scheme, credentials are vended as before.+ CatalogWrapperForREST withProvider =+ new CatalogWrapperForREST(+ "with-provider",+ new IcebergConfig(+ ImmutableMap.of(+ IcebergConstants.CATALOG_BACKEND, "memory",+ IcebergConstants.WAREHOUSE, "/tmp/warehouse",+ CredentialConstants.CREDENTIAL_PROVIDERS,+ DummyCredentialProvider.DUMMY_CREDENTIAL_TYPE)));+ ((SupportsNamespaces) withProvider.getCatalog()).createNamespace(namespace);+ withProvider+ .getCatalog()+ .createTable(+ table,+ schema,+ PartitionSpec.unpartitioned(),+ "s3://bucket/wh/db/tbl",+ Collections.emptyMap());+ Assertions.assertTrue(+ withProvider.shouldGenerateCredential(+ withProvider.loadTable(table, false, CredentialPrivilege.READ), true));+ }+@Testvoid testLocalTableCredentials() {IcebergConfig config =diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.javanew file mode 100644index 0000000000..84b11e5ec1--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java@@ -0,0 +1,183 @@+/*+ * 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.iceberg.service;++import com.google.common.collect.ImmutableList;+import com.google.common.collect.ImmutableMap;+import java.util.List;+import java.util.stream.Collectors;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;+import org.apache.gravitino.iceberg.common.IcebergConfig;+import org.apache.iceberg.DataFiles;+import org.apache.iceberg.DeleteFile;+import org.apache.iceberg.FileScanTask;+import org.apache.iceberg.PartitionSpec;+import org.apache.iceberg.Schema;+import org.apache.iceberg.Table;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.catalog.SupportsNamespaces;+import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.ServiceFailureException;+import org.apache.iceberg.expressions.Expression;+import org.apache.iceberg.expressions.Expressions;+import org.apache.iceberg.rest.requests.PlanTableScanRequest;+import org.apache.iceberg.rest.responses.PlanTableScanResponse;+import org.apache.iceberg.types.Types;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++/** Tests server-side scan planning against the REST spec's request semantics. */+public class TestIcebergScanPlanning {++ private static final TableIdentifier IDENT = TableIdentifier.of(Namespace.of("db"), "t");++ private CatalogWrapperForREST wrapper;+ private Table table;++ @BeforeEach+ public void setUp() {+ wrapper =+ new CatalogWrapperForREST(+ "scan-test",+ new IcebergConfig(+ ImmutableMap.of(+ IcebergConstants.CATALOG_BACKEND, "memory",+ IcebergConstants.WAREHOUSE, "/tmp/warehouse")));+ ((SupportsNamespaces) wrapper.getCatalog()).createNamespace(Namespace.of("db"));+ table =+ wrapper+ .getCatalog()+ .createTable(+ IDENT,+ new Schema(+ Types.NestedField.required(1, "id", Types.LongType.get()),+ Types.NestedField.optional(2, "a", Types.StringType.get())),+ PartitionSpec.unpartitioned());+ }++ @Test+ public void testIncrementalScanStartIsExclusive() {+ long s1 = append("/data/f1.parquet");+ append("/data/f2.parquet");+ long s3 = append("/data/f3.parquet");++ Assertions.assertEquals(+ ImmutableList.of("/data/f2.parquet", "/data/f3.parquet"),+ planFiles(PlanTableScanRequest.builder().withStartSnapshotId(s1).withEndSnapshotId(s3)));+ Assertions.assertEquals(+ ImmutableList.of(),+ planFiles(PlanTableScanRequest.builder().withStartSnapshotId(s3).withEndSnapshotId(s3)));+ }++ @Test+ public void testInvalidFilterAndStatsFieldsAreClientErrors() {+ append("/data/f1.parquet");+ IllegalArgumentException unknownColumn =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ planFiles(PlanTableScanRequest.builder().withFilter(Expressions.equal("nope", 1))));+ Assertions.assertFalse(+ unknownColumn.getMessage().contains("struct<"), unknownColumn.getMessage());++ // Case-sensitive by default.+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> planFiles(PlanTableScanRequest.builder().withFilter(Expressions.equal("ID", 1L))));++ IllegalArgumentException unknownStats =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ planFiles(+ PlanTableScanRequest.builder().withStatsFields(ImmutableList.of("nope"))));+ Assertions.assertTrue(unknownStats.getMessage().contains("nope"), unknownStats.getMessage());+ Assertions.assertFalse(+ unknownStats.getMessage().contains("NullPointerException"), unknownStats.getMessage());+ }++ @Test+ public void testConstantFiltersInTheSpecFormAreAccepted() throws Exception {+ PlanTableScanRequest request =+ IcebergObjectMapper.getInstance()+ .readValue(+ "{\"filter\":{\"type\":\"not\",\"child\":{\"type\":\"or\","+ + "\"left\":{\"type\":\"false\"},\"right\":{\"type\":\"false\"}}}}",+ PlanTableScanRequest.class);+ Assertions.assertEquals(Expression.Operation.TRUE, request.filter().op());++ PlanTableScanRequest alsoAccepted =+ IcebergObjectMapper.getInstance()+ .readValue("{\"filter\":true}", PlanTableScanRequest.class);+ Assertions.assertEquals(Expression.Operation.TRUE, alsoAccepted.filter().op());+ }++ @Test+ public void testDeletionVectorsSharingAFileAreRefused() {+ DeleteFile dv1 = deletionVector("/data/dv.puffin", 4L, "/data/f1.parquet");+ DeleteFile dv2 = deletionVector("/data/dv.puffin", 120L, "/data/f2.parquet");+ FileScanTask task1 = Mockito.mock(FileScanTask.class);+ Mockito.when(task1.deletes()).thenReturn(ImmutableList.of(dv1));+ FileScanTask task2 = Mockito.mock(FileScanTask.class);+ Mockito.when(task2.deletes()).thenReturn(ImmutableList.of(dv2));++ Assertions.assertThrows(+ ServiceFailureException.class,+ () ->+ CatalogWrapperForREST.checkDeleteFilesCanBeReferenced(+ IDENT, ImmutableList.of(task1, task2)));+ // The same delete file shared by tasks is fine.+ Assertions.assertDoesNotThrow(+ () ->+ CatalogWrapperForREST.checkDeleteFilesCanBeReferenced(+ IDENT, ImmutableList.of(task1, task1)));+ }++ private static DeleteFile deletionVector(String location, long offset, String dataFile) {+ DeleteFile file = Mockito.mock(DeleteFile.class);+ Mockito.when(file.location()).thenReturn(location);+ Mockito.when(file.contentOffset()).thenReturn(offset);+ Mockito.when(file.referencedDataFile()).thenReturn(dataFile);+ return file;+ }++ private long append(String path) {+ table+ .newFastAppend()+ .appendFile(+ DataFiles.builder(PartitionSpec.unpartitioned())+ .withPath(path)+ .withFileSizeInBytes(10)+ .withRecordCount(1)+ .build())+ .commit();+ table.refresh();+ return table.currentSnapshot().snapshotId();+ }++ private List<String> planFiles(PlanTableScanRequest.Builder request) {+ PlanTableScanResponse response = wrapper.planTableScan(IDENT, request.build());+ return response.fileScanTasks().stream()+ .map(task -> task.file().location())+ .sorted()+ .collect(Collectors.toList());+ }+}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.javanew file mode 100644index 0000000000..52abb08efd--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.java@@ -0,0 +1,47 @@+/*+ * 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.iceberg.service.dispatcher;++import java.time.Instant;+import org.apache.gravitino.meta.AuditInfo;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestIcebergEntityAuditUtils {++ @Test+ public void testCreatorIsSetOnlyWhenMissing() {+ Instant now = Instant.now();+ AuditInfo empty = IcebergEntityAuditUtils.withCreator(AuditInfo.EMPTY, "alice", now);+ Assertions.assertEquals("alice", empty.creator());+ Assertions.assertEquals(now, empty.createTime());+ Assertions.assertNull(empty.lastModifier());++ AuditInfo modifiedOnly =+ AuditInfo.builder().withLastModifier("bob").withLastModifiedTime(now).build();+ AuditInfo filled = IcebergEntityAuditUtils.withCreator(modifiedOnly, "alice", now);+ Assertions.assertEquals("alice", filled.creator());+ Assertions.assertEquals("bob", filled.lastModifier());++ AuditInfo reported =+ AuditInfo.builder().withCreator("carol").withCreateTime(Instant.EPOCH).build();+ Assertions.assertSame(+ reported, IcebergEntityAuditUtils.withCreator(reported, "alice", Instant.now()));+ }+}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 a78ecbe90e..f5f4ef801b 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@@ -50,6 +50,7 @@ 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.gravitino.meta.SchemaEntity;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;@@ -513,7 +514,7 @@ public class TestIcebergNamespaceHookDispatcher {}@Test- public void testCreateNestedNamespaceOwnsMissingAncestorsAndLeaf() {+ public void testCreateNestedNamespaceOwnsMissingAncestorsAndLeaf() throws IOException {// 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");@@ -542,6 +543,14 @@ public class TestIcebergNamespaceHookDispatcher {Assertions.assertEquals(Arrays.asList(TEST_CATALOG + ".A:B", TEST_CATALOG + ".A:B:C", TEST_CATALOG + ".A:B:C:D"),names);++ // Each namespace the request created gets its creator recorded; the existing A does not.+ ArgumentCaptor<NameIdentifier> recorded = ArgumentCaptor.forClass(NameIdentifier.class);+ verify(mockEntityStore, times(3))+ .update(recorded.capture(), eq(SchemaEntity.class), eq(Entity.EntityType.SCHEMA), any());+ Assertions.assertEquals(+ Arrays.asList("A:B", "A:B:C", "A:B:C:D"),+ recorded.getAllValues().stream().map(NameIdentifier::name).collect(Collectors.toList()));}@Testdiff --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 0b37b8e3fc..d72cc3f880 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@@ -39,6 +39,8 @@ import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.iceberg.common.IcebergConfig;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.listener.api.event.IcebergRequestContext;import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Schema;@@ -46,6 +48,7 @@ import org.apache.iceberg.TableMetadata;import org.apache.iceberg.TableMetadataParser;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;import org.apache.iceberg.rest.requests.ImmutableRegisterTableRequest;import org.apache.iceberg.rest.requests.RegisterTableRequest;@@ -401,4 +404,33 @@ public class TestIcebergNamespaceOperationExecutor {Files.writeString(metadataFile, TableMetadataParser.toJson(metadata), StandardCharsets.UTF_8);return metadataFile.toUri().toString();}++ @Test+ public void testCreateNamespaceRefusesSchemaSeparatorInLevelWithAuthorization() {+ IcebergConfigProvider provider = mock(IcebergConfigProvider.class);+ when(provider.getMetalakeName()).thenReturn("metalake");+ when(provider.getDefaultCatalogName()).thenReturn("test_catalog");+ when(mockContext.userName()).thenReturn("user");+ when(mockCatalogWrapper.createNamespace(any())).thenReturn(mock(CreateNamespaceResponse.class));+ try {+ IcebergRESTServerContext.create(provider, true, false, false, mockWrapperManager);+ CreateNamespaceRequest colliding =+ CreateNamespaceRequest.builder().withNamespace(Namespace.of("x:y")).build();+ Assertions.assertThrows(+ BadRequestException.class, () -> executor.createNamespace(mockContext, colliding));+ verify(mockCatalogWrapper, never()).createNamespace(any());++ // The nested namespace the level would collide with is still accepted.+ executor.createNamespace(+ mockContext,+ CreateNamespaceRequest.builder().withNamespace(Namespace.of("x", "y")).build());+ verify(mockCatalogWrapper).createNamespace(any());++ // Without authorization there is no Gravitino schema to collide with.+ IcebergRESTServerContext.create(provider, false, false, false, mockWrapperManager);+ Assertions.assertDoesNotThrow(() -> executor.createNamespace(mockContext, colliding));+ } finally {+ IcebergRESTServerContext.create(provider, false, false, false, null);+ }+ }}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnerPropertyGuard.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnerPropertyGuard.javanew file mode 100644index 0000000000..ffbe4f11a9--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergOwnerPropertyGuard.java@@ -0,0 +1,105 @@+/*+ * 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.iceberg.service.dispatcher;++import com.google.common.collect.ImmutableMap;+import com.google.common.collect.ImmutableSet;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import org.apache.iceberg.MetadataUpdate;+import org.apache.iceberg.UpdateRequirement;+import org.apache.iceberg.rest.requests.UpdateNamespacePropertiesRequest;+import org.apache.iceberg.rest.requests.UpdateTableRequest;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestIcebergOwnerPropertyGuard {++ @Test+ public void testCommitCannotChangeTheOwnerProperty() {+ UpdateTableRequest request =+ new UpdateTableRequest(+ Collections.emptyList(),+ Arrays.asList(+ new MetadataUpdate.SetProperties(ImmutableMap.of("owner", "mallory", "k", "v")),+ new MetadataUpdate.RemoveProperties(ImmutableSet.of("owner")),+ new MetadataUpdate.SetCurrentSchema(0)));++ List<MetadataUpdate> updates = IcebergOwnerPropertyGuard.protect(request, "bob").updates();++ Assertions.assertEquals(2, updates.size());+ Assertions.assertEquals(+ ImmutableMap.of("k", "v"), ((MetadataUpdate.SetProperties) updates.get(0)).updated());+ Assertions.assertInstanceOf(MetadataUpdate.SetCurrentSchema.class, updates.get(1));+ }++ @Test+ public void testCreateCommitSetsTheOwnerToTheCommitter() {+ UpdateTableRequest request =+ new UpdateTableRequest(+ Collections.singletonList(new UpdateRequirement.AssertTableDoesNotExist()),+ Collections.singletonList(+ new MetadataUpdate.SetProperties(ImmutableMap.of("owner", "spark_user"))));++ MetadataUpdate.SetProperties update =+ (MetadataUpdate.SetProperties)+ IcebergOwnerPropertyGuard.protect(request, "bob").updates().get(0);++ Assertions.assertEquals(ImmutableMap.of("owner", "bob"), update.updated());+ }++ @Test+ public void testRequestsWithoutTheOwnerPropertyOrUserAreUnchanged() {+ UpdateTableRequest request =+ new UpdateTableRequest(+ Collections.emptyList(),+ Collections.singletonList(new MetadataUpdate.SetProperties(ImmutableMap.of("k", "v"))));+ Assertions.assertSame(request, IcebergOwnerPropertyGuard.protect(request, "bob"));++ UpdateTableRequest withOwner =+ new UpdateTableRequest(+ Collections.emptyList(),+ Collections.singletonList(+ new MetadataUpdate.SetProperties(ImmutableMap.of("owner", "x"))));+ Assertions.assertSame(withOwner, IcebergOwnerPropertyGuard.protect(withOwner, "anonymous"));+ }++ @Test+ public void testNamespaceUpdateCannotChangeTheOwnerProperty() {+ UpdateNamespacePropertiesRequest request =+ UpdateNamespacePropertiesRequest.builder()+ .update("owner", "mallory")+ .update("k", "v")+ .remove("old")+ .build();++ UpdateNamespacePropertiesRequest protectedRequest =+ IcebergOwnerPropertyGuard.protect(request, "bob");++ Assertions.assertEquals(ImmutableMap.of("k", "v"), protectedRequest.updates());+ Assertions.assertEquals(Collections.singletonList("old"), protectedRequest.removals());++ UpdateNamespacePropertiesRequest removal =+ IcebergOwnerPropertyGuard.protect(+ UpdateNamespacePropertiesRequest.builder().remove("owner").remove("old").build(),+ "bob");+ Assertions.assertEquals(Collections.singletonList("old"), removal.removals());+ }+}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 7cdd799a02..9b873c47ce 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@@ -28,11 +28,13 @@ import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.time.Instant;import java.util.Arrays;import java.util.Collections;import java.util.List;+import java.util.function.Function;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;@@ -53,6 +55,7 @@ import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLock;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.TableEntity;+import org.apache.iceberg.MetadataUpdate;import org.apache.iceberg.Schema;import org.apache.iceberg.UpdateRequirement;import org.apache.iceberg.catalog.Namespace;@@ -583,6 +586,79 @@ public class TestIcebergTableHookDispatcher {Assertions.assertEquals(TEST_USER, userCaptor.getValue());}+ @Test+ @SuppressWarnings("unchecked")+ public void testCreateTableRecordsTheCreator() throws IOException {+ Namespace namespace = Namespace.of("test_schema");+ CreateTableRequest request =+ CreateTableRequest.builder().withName("test_table").withSchema(TABLE_SCHEMA).build();+ when(mockDispatcher.createTable(mockContext, namespace, request))+ .thenReturn(mock(LoadTableResponse.class));++ hookDispatcher.createTable(mockContext, namespace, request);++ NameIdentifier identifier =+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, TableIdentifier.of(namespace, "test_table"), ":");+ ArgumentCaptor<Function<TableEntity, TableEntity>> updater =+ ArgumentCaptor.forClass(Function.class);+ verify(mockEntityStore)+ .update(+ eq(identifier), eq(TableEntity.class), eq(Entity.EntityType.TABLE), updater.capture());+ TableEntity imported =+ TableEntity.builder()+ .withId(1L)+ .withName("test_table")+ .withNamespace(identifier.namespace())+ .withColumns(Collections.emptyList())+ .withAuditInfo(AuditInfo.EMPTY)+ .build();+ TableEntity recorded = updater.getValue().apply(imported);+ Assertions.assertEquals(TEST_USER, recorded.auditInfo().creator());+ Assertions.assertNotNull(recorded.auditInfo().createTime());+ Assertions.assertEquals(imported.id(), recorded.id());+ }++ @Test+ public void testSchemaChangeCommitSyncsColumnsWhileRunningAsTheCommitter() {+ TableIdentifier tableId = TableIdentifier.of("test_schema", "test_table");+ Schema newSchema =+ new Schema(+ 1,+ NestedField.required(1, "test_field", StringType.get()),+ NestedField.optional(2, "c", StringType.get()));+ UpdateTableRequest request =+ new UpdateTableRequest(+ Collections.emptyList(),+ Arrays.asList(+ new MetadataUpdate.AddSchema(newSchema), new MetadataUpdate.SetCurrentSchema(-1)));+ when(mockDispatcher.updateTable(mockContext, tableId, request))+ .thenReturn(mock(LoadTableResponse.class));++ hookDispatcher.updateTable(mockContext, tableId, request);++ verify(mockInternalTableDispatcher)+ .loadTable(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, tableId, ":"));+ verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ }++ @Test+ public void testOnlySchemaUpdatesCountAsSchemaChanges() {+ Assertions.assertFalse(+ IcebergTableHookDispatcher.changesSchema(+ new UpdateTableRequest(+ Collections.emptyList(),+ Collections.singletonList(+ new MetadataUpdate.SetProperties(ImmutableMap.of("k", "v"))))));+ Assertions.assertTrue(+ IcebergTableHookDispatcher.changesSchema(+ new UpdateTableRequest(+ Collections.emptyList(),+ Collections.singletonList(new MetadataUpdate.SetCurrentSchema(0)))));+ }+@Testpublic void testUpdateTableSkipsImportForRegularUpdate() {TableIdentifier tableId = TableIdentifier.of("test_schema", "test_table");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 d81cf9fee0..bec9071dc1 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@@ -184,6 +184,10 @@ public class TestIcebergViewHookDispatcher {verify(mockInternalViewDispatcher, times(1)).loadView(eq(expectedIdent));verify(mockViewDispatcher, never()).loadView(any());+ // Verify the creator was recorded on the imported view+ verify(mockEntityStore)+ .update(eq(expectedIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any());+// Verify ownership was setverify(mockInternalOwnerDispatcher, times(1)).setOwner(any(), any(), eq(USER), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceListFilter.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceListFilter.javanew file mode 100644index 0000000000..2ca296acb6--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceListFilter.java@@ -0,0 +1,75 @@+/*+ * 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.iceberg.service.rest;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;++import java.util.Arrays;+import java.util.List;+import java.util.Set;+import java.util.function.Function;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.rest.responses.ListNamespacesResponse;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;+import org.mockito.Mockito;++/** Tests that the authorization filter returns listed namespaces unchanged. */+public class TestIcebergNamespaceListFilter {++ @Test+ public void testLevelContainingSeparatorIsNotSplit() {+ List<Namespace> listed =+ Arrays.asList(Namespace.of("x:y"), Namespace.of("x", "y"), Namespace.of("a"));+ ListNamespacesResponse response = ListNamespacesResponse.builder().addAll(listed).build();++ // Everything visible: the namespaces come back exactly as listed.+ Assertions.assertEquals(listed, filter(response, null).namespaces());++ // Only the Gravitino schema "a" is visible.+ Assertions.assertEquals(+ Arrays.asList(Namespace.of("a")),+ filter(response, Set.of(NameIdentifier.of("m", "c", "a"))).namespaces());+ }++ @SuppressWarnings("unchecked")+ private static ListNamespacesResponse filter(+ ListNamespacesResponse response, Set<NameIdentifier> visible) {+ try (MockedStatic<MetadataAuthzHelper> helper = Mockito.mockStatic(MetadataAuthzHelper.class)) {+ helper+ .when(+ () ->+ MetadataAuthzHelper.filterByExpression(+ anyString(), anyString(), any(), any(Namespace[].class), any(Function.class)))+ .thenAnswer(+ invocation -> {+ Namespace[] namespaces = invocation.getArgument(3);+ Function<Namespace, NameIdentifier> toIdent = invocation.getArgument(4);+ return Arrays.stream(namespaces)+ .filter(ns -> visible == null || visible.contains(toIdent.apply(ns)))+ .toArray(Namespace[]::new);+ });+ return IcebergNamespaceOperations.filterListNamespacesResponse(response, "m", "c");+ }+ }+}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceOperations.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceOperations.javaindex 9db34be734..dc4c890ae3 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceOperations.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergNamespaceOperations.java@@ -397,6 +397,21 @@ public class TestIcebergNamespaceOperations extends IcebergNamespaceTestBase {verifyUpdateNamespaceSucc(Namespace.of("update_foo3", "a"));}+ @Test+ void testUpdateNamespaceRejectsNullPropertyValue() {+ verifyCreateNamespaceSucc("update_null_value");+ Response response =+ getUpdateNamespaceClientBuilder(Namespace.of("update_null_value"))+ .post(+ Entity.entity(+ "{\"removals\":[],\"updates\":{\"k\":null}}", MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(400, response.getStatus());++ // Nothing was stored, so the namespace can still be loaded and changed.+ verifyLoadNamespaceSucc(Namespace.of("update_null_value"));+ verifyUpdateNamespaceSucc(Namespace.of("update_null_value"));+ }+@Testvoid testRegisterTableWithCredentialVending() {// register without credential vending -- no credentials in response@@ -428,36 +443,30 @@ public class TestIcebergNamespaceOperations extends IcebergNamespaceTestBase {}@Test- void testRegisterTableRemoteSigningNotSupported() {+ void testRegisterTableWithOtherAccessDelegationIsNotRefused() {RegisterTableRequest request =ImmutableRegisterTableRequest.builder().name("remote_signing_test").metadataLocation("mock").build();- Response response =+ // A delegation mechanism the server does not offer does not change the outcome: the request+ // is handled exactly as without the header.+ int withoutHeader =getNamespaceClientBuilder(Optional.of(Namespace.of("register_remote_ns")),Optional.of("register"),Optional.empty())- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "remote-signing")- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));- Assertions.assertEquals(406, response.getStatus());- }-- @Test- void testRegisterTableInvalidAccessDelegation() {- RegisterTableRequest request =- ImmutableRegisterTableRequest.builder()- .name("invalid_delegation_test")- .metadataLocation("mock")- .build();- Response response =- getNamespaceClientBuilder(- Optional.of(Namespace.of("register_invalid_ns")),- Optional.of("register"),- Optional.empty())- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "invalid-value")- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));- Assertions.assertEquals(400, response.getStatus());+ .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))+ .getStatus();+ for (String header : new String[] {"remote-signing", "invalid-value"}) {+ Response response =+ getNamespaceClientBuilder(+ Optional.of(Namespace.of("register_remote_ns")),+ Optional.of("register"),+ Optional.empty())+ .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, header)+ .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(withoutHeader, response.getStatus(), header);+ }}}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergTableOperations.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergTableOperations.javaindex 16641ffc41..348d085ad8 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergTableOperations.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergTableOperations.java@@ -68,12 +68,16 @@ import org.apache.gravitino.listener.api.event.IcebergPlanTableScanPreEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTableEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTableFailureEvent;import org.apache.gravitino.listener.api.event.IcebergRenameTablePreEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsFailureEvent;+import org.apache.gravitino.listener.api.event.IcebergReportTableMetricsPreEvent;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.listener.api.event.IcebergTableExistsEvent;import org.apache.gravitino.listener.api.event.IcebergTableExistsPreEvent;import org.apache.gravitino.listener.api.event.IcebergUpdateTableEvent;import org.apache.gravitino.listener.api.event.IcebergUpdateTableFailureEvent;import org.apache.gravitino.listener.api.event.IcebergUpdateTablePreEvent;+import org.apache.gravitino.listener.api.event.OperationType;import org.apache.gravitino.server.ServerConfig;import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;import org.apache.iceberg.GenericBlobMetadata;@@ -116,6 +120,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.MethodSource;import org.mockito.Mockito;+import org.opentest4j.AssertionFailedError;@SuppressWarnings("deprecation")public class TestIcebergTableOperations extends IcebergNamespaceTestBase {@@ -524,11 +529,19 @@ public class TestIcebergTableOperations extends IcebergNamespaceTestBase {.commitMetrics(commitMetrics).build();ReportMetricsRequest request = ReportMetricsRequest.of(commitReport);+ dummyEventListener.clearEvent();Response response =getReportMetricsClientBuilder("metrics_foo1", namespace).post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));Assertions.assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());+ // The report is recorded as its own operation, with no table-exists event for the check.+ Assertions.assertInstanceOf(+ IcebergReportTableMetricsPreEvent.class, dummyEventListener.popPreEvent());+ Assertions.assertInstanceOf(+ IcebergReportTableMetricsEvent.class, dummyEventListener.popPostEvent());+ Assertions.assertThrows(AssertionFailedError.class, dummyEventListener::popPostEvent);+ Assertions.assertThrows(AssertionFailedError.class, dummyEventListener::popPreEvent);ReportMetricsRequest qualifiedRequest =ReportMetricsRequest.of(@@ -544,10 +557,14 @@ public class TestIcebergTableOperations extends IcebergNamespaceTestBase {.post(Entity.entity(qualifiedRequest, MediaType.APPLICATION_JSON_TYPE));Assertions.assertEquals(Status.NO_CONTENT.getStatusCode(), qualifiedResponse.getStatus());+ dummyEventListener.clearEvent();Response missingTableResponse =getReportMetricsClientBuilder("missing_metrics_table", namespace).post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), missingTableResponse.getStatus());+ Event failure = dummyEventListener.popPostEvent();+ Assertions.assertInstanceOf(IcebergReportTableMetricsFailureEvent.class, failure);+ Assertions.assertEquals(OperationType.REPORT_TABLE_METRICS, failure.operationType());ReportMetricsRequest mismatchedRequest =ReportMetricsRequest.of(@@ -1004,27 +1021,36 @@ public class TestIcebergTableOperations extends IcebergNamespaceTestBase {@ParameterizedTest@MethodSource("org.apache.gravitino.iceberg.service.rest.IcebergRestTestUtil#testNamespaces")- void testRemoteSigningNotSupported(Namespace namespace) {+ void testAccessDelegationListIsServed(Namespace namespace) {verifyCreateNamespaceSucc(namespace);- // Attempt to create table with "remote-signing" access delegation- // This should fail with UnsupportedOperationException -> 406 Not Acceptable- CreateTableRequest createTableRequest =- CreateTableRequest.builder()- .withName("test_remote_signing")- .withSchema(tableSchema)- .build();-- Response response =- getTableClientBuilder(namespace, Optional.empty())- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "remote-signing")- .post(Entity.entity(createTableRequest, MediaType.APPLICATION_JSON_TYPE));-- Assertions.assertEquals(406, response.getStatus());- String errorBody = response.readEntity(String.class);- Assertions.assertTrue(- errorBody.contains("remote signing") || errorBody.contains("remote-signing"),- "Error message should mention remote signing: " + errorBody);+ // The header lists the mechanisms the client supports; the server serves the request with the+ // ones it offers, or none. remote-signing alone, a comma-separated list in either order, and an+ // unknown mechanism are all served.+ String[] headers = {+ "remote-signing",+ "vended-credentials,remote-signing",+ "remote-signing, vended-credentials",+ "invalid-value"+ };+ for (int i = 0; i < headers.length; i++) {+ CreateTableRequest createTableRequest =+ CreateTableRequest.builder()+ .withName("delegation_list_" + i)+ .withSchema(tableSchema)+ .build();+ Response create =+ getTableClientBuilder(namespace, Optional.empty())+ .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, headers[i])+ .post(Entity.entity(createTableRequest, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Status.OK.getStatusCode(), create.getStatus(), headers[i]);++ Response load =+ getTableClientBuilder(namespace, Optional.of("delegation_list_" + i))+ .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, headers[i])+ .get();+ Assertions.assertEquals(Status.OK.getStatusCode(), load.getStatus(), headers[i]);+ }}@ParameterizedTest@@ -1061,29 +1087,18 @@ public class TestIcebergTableOperations extends IcebergNamespaceTestBase {verifyDropNamespaceSucc(namespace);}- @ParameterizedTest- @MethodSource("org.apache.gravitino.iceberg.service.rest.IcebergRestTestUtil#testNamespaces")- void testInvalidAccessDelegation(Namespace namespace) {- verifyCreateNamespaceSucc(namespace);-- // Attempt to create table with invalid access delegation value- // This should fail with IllegalArgumentException -> 400 Bad Request- CreateTableRequest createTableRequest =- CreateTableRequest.builder()- .withName("test_invalid_delegation")- .withSchema(tableSchema)- .build();-- Response response =- getTableClientBuilder(namespace, Optional.empty())- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "invalid-value")- .post(Entity.entity(createTableRequest, MediaType.APPLICATION_JSON_TYPE));-- Assertions.assertEquals(400, response.getStatus());- String errorBody = response.readEntity(String.class);+ @Test+ void testIsCredentialVendingParsesTheMechanismList() {+ Assertions.assertFalse(IcebergTableOperations.isCredentialVending(null));+ Assertions.assertFalse(IcebergTableOperations.isCredentialVending(" "));+ Assertions.assertFalse(IcebergTableOperations.isCredentialVending("remote-signing"));+ Assertions.assertFalse(IcebergTableOperations.isCredentialVending("invalid-value"));+ Assertions.assertTrue(IcebergTableOperations.isCredentialVending("vended-credentials"));+ Assertions.assertTrue(IcebergTableOperations.isCredentialVending("VENDED-CREDENTIALS"));+ Assertions.assertTrue(+ IcebergTableOperations.isCredentialVending("vended-credentials,remote-signing"));Assertions.assertTrue(- errorBody.contains("vended-credentials") && errorBody.contains("illegal"),- "Error message should mention valid values: " + errorBody);+ IcebergTableOperations.isCredentialVending("remote-signing , vended-credentials"));}@ParameterizedTest@@ -1800,36 +1815,17 @@ public class TestIcebergTableOperations extends IcebergNamespaceTestBase {@ParameterizedTest@MethodSource("org.apache.gravitino.iceberg.service.rest.IcebergRestTestUtil#testNamespaces")- void testPlanTableScanRemoteSigningNotSupported(Namespace namespace) {+ void testPlanTableScanWithOtherAccessDelegationIsServed(Namespace namespace) {verifyCreateNamespaceSucc(namespace);verifyCreateTableSucc(namespace, "scan_remote_signing");PlanTableScanRequest request = PlanTableScanRequest.builder().build();- Response response =- getTableClientBuilder(namespace, Optional.of("scan_remote_signing/plan"))- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "remote-signing")- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));- Assertions.assertEquals(406, response.getStatus());- String errorBody = response.readEntity(String.class);- Assertions.assertTrue(- errorBody.contains("remote signing") || errorBody.contains("remote-signing"),- "Error message should mention remote signing: " + errorBody);- }-- @ParameterizedTest- @MethodSource("org.apache.gravitino.iceberg.service.rest.IcebergRestTestUtil#testNamespaces")- void testPlanTableScanInvalidAccessDelegation(Namespace namespace) {- verifyCreateNamespaceSucc(namespace);- verifyCreateTableSucc(namespace, "scan_invalid_delegation");- PlanTableScanRequest request = PlanTableScanRequest.builder().build();- Response response =- getTableClientBuilder(namespace, Optional.of("scan_invalid_delegation/plan"))- .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, "invalid-value")- .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));- Assertions.assertEquals(400, response.getStatus());- String errorBody = response.readEntity(String.class);- Assertions.assertTrue(- errorBody.contains("vended-credentials") && errorBody.contains("illegal"),- "Error message should mention valid values: " + errorBody);+ for (String header : new String[] {"remote-signing", "invalid-value"}) {+ Response response =+ getTableClientBuilder(namespace, Optional.of("scan_remote_signing/plan"))+ .header(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION, header)+ .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Status.OK.getStatusCode(), response.getStatus(), header);+ }}private Response doPlanTableScanWithCredentialVending(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 990783110f..b9d25aa64b 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@@ -47,10 +47,12 @@ import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;import org.apache.gravitino.iceberg.service.IcebergRESTUtils;import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;+import org.apache.gravitino.iceberg.service.rest.IcebergConfigOperations;import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.catalog.Catalog;@@ -60,6 +62,8 @@ import org.apache.iceberg.rest.RESTCatalog;import org.apache.iceberg.rest.RESTUtil;import org.apache.iceberg.rest.requests.ReportMetricsRequest;import org.apache.iceberg.rest.responses.ErrorResponse;+import org.glassfish.hk2.api.ActiveDescriptor;+import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;@@ -304,6 +308,58 @@ public class TestIcebergMetadataAuthorizationMethodInterceptor {Mockito.verify(invocation, Mockito.times(1)).proceed();}+ @Test+ public void testNonIcebergCatalogDoesNotSkipAuthorization() {+ // A prefix naming a catalog of another kind is authorized normally instead of failing with+ // an internal error inside the authorization step.+ IcebergCatalogWrapperManager wrapperManager = Mockito.mock(IcebergCatalogWrapperManager.class);+ Mockito.when(wrapperManager.getCatalogWrapper("glue_catalog"))+ .thenThrow(new IllegalArgumentException("Catalog glue_catalog is not an Iceberg catalog"));+ resetContext(wrapperManager, true);++ IcebergMetadataAuthorizationMethodInterceptor interceptor =+ new IcebergMetadataAuthorizationMethodInterceptor();+ assertFalse(+ interceptor.shouldSkipAuthorization(+ Map.of(Entity.EntityType.CATALOG, NameIdentifier.of(TEST_METALAKE, "glue_catalog"))));+ }++ @Test+ public void testConfigEndpointIsAuthorizedOnTheWarehouseCatalog() throws Exception {+ Assertions.assertTrue(+ new IcebergRESTAuthInterceptionService()+ .getDescriptorFilter()+ .matches(descriptorFor(IcebergConfigOperations.class)));++ Method getConfig = IcebergConfigOperations.class.getMethod("getConfig", String.class);+ AuthorizationExpression expression = getConfig.getAnnotation(AuthorizationExpression.class);+ assertNotNull(expression);+ assertEquals(+ AuthorizationExpressionConstants.LOAD_CATALOG_AUTHORIZATION_EXPRESSION,+ expression.expression());++ IcebergMetadataAuthorizationMethodInterceptor interceptor =+ new IcebergMetadataAuthorizationMethodInterceptor();+ // The warehouse names the catalog; an empty warehouse means the default catalog.+ assertEquals(+ NameIdentifierUtil.ofCatalog(TEST_METALAKE, "other_catalog"),+ interceptor+ .extractNameIdentifierFromParameters(+ getConfig.getParameters(), new Object[] {"other_catalog"})+ .get(Entity.EntityType.CATALOG));+ assertEquals(+ NameIdentifierUtil.ofCatalog(TEST_METALAKE, TEST_CATALOG),+ interceptor+ .extractNameIdentifierFromParameters(getConfig.getParameters(), new Object[] {""})+ .get(Entity.EntityType.CATALOG));+ }++ private static ActiveDescriptor<?> descriptorFor(Class<?> clazz) {+ ActiveDescriptor<?> descriptor = Mockito.mock(ActiveDescriptor.class);+ Mockito.when(descriptor.getImplementation()).thenReturn(clazz.getName());+ return descriptor;+ }+@Testpublic void testMetricsReportDoesNotSkipAuthorizationForRestCatalog() throws Exception {IcebergCatalogWrapperManager wrapperManager = Mockito.mock(IcebergCatalogWrapperManager.class);@@ -479,8 +535,10 @@ public class TestIcebergMetadataAuthorizationMethodInterceptor {public void testInvokeShouldSkipAuthorizationWrapperLookupFailureReturnsAuthInternalError()throws Throwable {IcebergCatalogWrapperManager wrapperManager = Mockito.mock(IcebergCatalogWrapperManager.class);+ // An unexpected lookup failure is a server error. (An IllegalArgumentException, such as a+ // prefix naming a catalog that is not an Iceberg catalog, is authorized normally instead.)Mockito.when(wrapperManager.getCatalogWrapper(TEST_CATALOG))- .thenThrow(new IllegalArgumentException("wrapper lookup failed"));+ .thenThrow(new IllegalStateException("wrapper lookup failed"));resetContext(wrapperManager, true);Method method =diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestLoadTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestLoadTableAuthzHandler.javaindex 976fc7fcda..ce94c9c250 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestLoadTableAuthzHandler.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestLoadTableAuthzHandler.java@@ -22,6 +22,8 @@ package org.apache.gravitino.server.web.filter;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -47,12 +49,14 @@ import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.iceberg.Schema;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.ForbiddenException;import org.apache.iceberg.exceptions.NoSuchTableException;import org.apache.iceberg.exceptions.ServiceUnavailableException;import org.apache.iceberg.inmemory.InMemoryCatalog;import org.apache.iceberg.types.Types;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;import org.mockito.Mockito;/** Test for {@link LoadTableAuthzHandler}. */@@ -155,6 +159,63 @@ public class TestLoadTableAuthzHandler {assertDoesNotThrow(() -> handler.process(baseIdentifierMap()));}+ @Test+ public void testViewNameIsForbiddenToCallersWhoCannotSeeTheView() throws Exception {+ InMemoryCatalog catalog = newCatalog();+ resetContextWithView(catalog);+ LoadTableAuthzHandler handler = createHandler(new Object[] {TEST_CATALOG + "/", "db", "v"});++ try (MockedStatic<IcebergLoadAuthzHandlerHelper> helper =+ Mockito.mockStatic(IcebergLoadAuthzHandlerHelper.class, Mockito.CALLS_REAL_METHODS)) {+ helper+ .when(() -> IcebergLoadAuthzHandlerHelper.isAllowed(any(), anyString()))+ .thenReturn(false);+ helper+ .when(() -> IcebergLoadAuthzHandlerHelper.isAllowed(any(), anyString(), any()))+ .thenReturn(false);++ // Same answer as for a table the caller may not load, so the view's name is not revealed.+ assertThrows(ForbiddenException.class, () -> handler.process(baseIdentifierMap()));+ }+ }++ @Test+ public void testViewNameIs404ToCallersWhoCanSeeTheView() throws Exception {+ InMemoryCatalog catalog = newCatalog();+ resetContextWithView(catalog);+ LoadTableAuthzHandler handler = createHandler(new Object[] {TEST_CATALOG + "/", "db", "v"});++ try (MockedStatic<IcebergLoadAuthzHandlerHelper> helper =+ Mockito.mockStatic(IcebergLoadAuthzHandlerHelper.class, Mockito.CALLS_REAL_METHODS)) {+ helper+ .when(+ () ->+ IcebergLoadAuthzHandlerHelper.isAllowed(+ any(),+ eq(+ AuthorizationExpressionConstants+ .ICEBERG_LOAD_VIEW_AUTHORIZATION_EXPRESSION)))+ .thenReturn(true);+ helper+ .when(() -> IcebergLoadAuthzHandlerHelper.isAllowed(any(), anyString(), any()))+ .thenReturn(false);++ // The client falls back to /views/ on 404.+ assertThrows(NoSuchTableException.class, () -> handler.process(baseIdentifierMap()));+ }+ }++ private static void resetContextWithView(InMemoryCatalog catalog) {+ IcebergCatalogWrapperManager wrapperManager = Mockito.mock(IcebergCatalogWrapperManager.class);+ CatalogWrapperForREST catalogWrapper = Mockito.mock(CatalogWrapperForREST.class);+ when(wrapperManager.getCatalogWrapper(TEST_CATALOG)).thenReturn(catalogWrapper);+ when(catalogWrapper.getCatalog()).thenReturn(catalog);+ when(catalogWrapper.supportsViewOperations()).thenReturn(true);+ when(catalogWrapper.viewExists(TableIdentifier.of("db", "v"))).thenReturn(true);+ when(catalogWrapper.tableExists(any(TableIdentifier.class))).thenReturn(false);+ resetContext(wrapperManager);+ }+private static LoadTableAuthzHandler createHandler(Object[] args) throws Exception {Method method =TestOperations.class.getMethod("loadTable", String.class, String.class, String.class);diff --git a/server-common/src/main/java/org/apache/gravitino/server/web/filter/BaseMetadataAuthorizationMethodInterceptor.java b/server-common/src/main/java/org/apache/gravitino/server/web/filter/BaseMetadataAuthorizationMethodInterceptor.javaindex d7de2531dd..84734b1feb 100644--- a/server-common/src/main/java/org/apache/gravitino/server/web/filter/BaseMetadataAuthorizationMethodInterceptor.java+++ b/server-common/src/main/java/org/apache/gravitino/server/web/filter/BaseMetadataAuthorizationMethodInterceptor.java@@ -28,11 +28,15 @@ import java.util.Optional;import java.util.Set;import javax.ws.rs.HttpMethod;import org.apache.gravitino.Entity;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.auth.ActiveRoles;import org.apache.gravitino.authorization.AuthorizationRequestContext;import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.listener.EventBus;+import org.apache.gravitino.listener.api.event.EventSource;+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;import org.apache.gravitino.server.authorization.AuthorizationRequestScope;import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;@@ -210,6 +214,17 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {return shouldSkipAuthorization(nameIdentifierMap);}+ /**+ * Returns the server to which authorization denials are attributed in the audit log. A protocol+ * that returns a source here records each denied request as an {@link+ * AuthorizationDenialFailureEvent}, the same as the Gravitino API does.+ *+ * @return the event source of this protocol, or empty to record no denial events+ */+ protected Optional<EventSource> authorizationDenialEventSource() {+ return Optional.empty();+ }+/*** Hook for requests that must validate the current user and active roles but do not have a* metadata object on which to evaluate an expression. A protocol root-list request is a typical@@ -245,18 +260,23 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {private Object authorizeMethodInScope(Method method, Object[] args, MethodInvoker methodInvoker, AuthorizationRequestScope scope)throws Throwable {+ // The object and expression a denial is recorded against, set as authorization proceeds.+ NameIdentifier deniedObject = null;+ String deniedExpression = "";try {Parameter[] parameters = method.getParameters();AuthorizationExpression expressionAnnotation =method.getAnnotation(AuthorizationExpression.class);if (expressionAnnotation != null) {String expression = expressionAnnotation.expression();+ deniedExpression = expression;AuthorizationTarget target =resolveAuthorizationTarget(method, expressionAnnotation, parameters, args);Map<Entity.EntityType, NameIdentifier> nameIdentifierMap = target.nameIdentifiers();boolean skipStandardCheck = shouldSkipAuthorization(method, nameIdentifierMap);NameIdentifier metalakeIdent = nameIdentifierMap.get(Entity.EntityType.METALAKE);+ deniedObject = metalakeIdent;AuthorizationRequestContext authorizationRequestContext = new AuthorizationRequestContext();if (!skipStandardCheck && metalakeIdent != null) {@@ -308,6 +328,9 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {}}+ if (nameIdentifierMap.get(target.entityType()) != null) {+ deniedObject = nameIdentifierMap.get(target.entityType());+ }Optional<AuthorizationHandler> handler =createAuthorizationHandler(method, parameters, args);@@ -351,6 +374,9 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {}}} catch (Exception ex) {+ if (ex instanceof ForbiddenException) {+ dispatchAuthorizationDenial(deniedObject, method.getName(), deniedExpression);+ }if (ex instanceof ForbiddenException || isExceptionPropagate(ex)) {return toErrorResponse(method, args, ex);}@@ -370,4 +396,28 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {return toErrorResponse(method, args, e);}}++ private void dispatchAuthorizationDenial(+ NameIdentifier deniedObject, String methodName, String expression) {+ Optional<EventSource> eventSource = authorizationDenialEventSource();+ if (!eventSource.isPresent()) {+ return;+ }+ String user = PrincipalUtils.getCurrentUserName();+ // Recording the denial must never change the response the client gets.+ try {+ EventBus eventBus = GravitinoEnv.getInstance().eventBus();+ if (eventBus != null) {+ eventBus.dispatchEvent(+ new AuthorizationDenialFailureEvent(+ user, deniedObject, methodName, expression, eventSource.get()));+ }+ } catch (Exception e) {+ LOG.error(+ "Failed to dispatch authorization denial event for user {} on operation {}",+ user,+ methodName,+ e);+ }+ }}diff --git a/server-common/src/test/java/org/apache/gravitino/server/web/filter/TestBaseMetadataAuthorizationMethodInterceptor.java b/server-common/src/test/java/org/apache/gravitino/server/web/filter/TestBaseMetadataAuthorizationMethodInterceptor.javaindex 7a4c5e4a33..c757f767c5 100644--- a/server-common/src/test/java/org/apache/gravitino/server/web/filter/TestBaseMetadataAuthorizationMethodInterceptor.java+++ b/server-common/src/test/java/org/apache/gravitino/server/web/filter/TestBaseMetadataAuthorizationMethodInterceptor.java@@ -60,6 +60,10 @@ import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.authorization.GravitinoAuthorizer;import org.apache.gravitino.authorization.Privilege;import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.listener.EventBus;+import org.apache.gravitino.listener.api.event.BaseEvent;+import org.apache.gravitino.listener.api.event.EventSource;+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;import org.apache.gravitino.server.authorization.AuthorizationRequestScope;import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;@@ -73,6 +77,7 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;import org.mockito.MockedStatic;/** Tests for {@link BaseMetadataAuthorizationMethodInterceptor}. */@@ -178,6 +183,77 @@ public class TestBaseMetadataAuthorizationMethodInterceptor {verify(invocation, never()).proceed();}+ @Test+ public void testExpressionDenialIsRecordedAgainstTheTarget() throws Throwable {+ EventBus eventBus = mock(EventBus.class);+ try (MockedStatic<GravitinoEnv> envStatic = mockGravitinoEnv(eventBus)) {+ TestInterceptor interceptor = new TestInterceptor(Entity.EntityType.SCHEMA);+ interceptor.denialEventSource = Optional.of(EventSource.GRAVITINO_ICEBERG_REST_SERVER);++ assertInstanceOf(+ ForbiddenException.class,+ interceptor.invoke(invocation("canAccessMetadata", "authorized")));++ ArgumentCaptor<BaseEvent> event = ArgumentCaptor.forClass(BaseEvent.class);+ verify(eventBus).dispatchEvent(event.capture());+ AuthorizationDenialFailureEvent denial =+ assertInstanceOf(AuthorizationDenialFailureEvent.class, event.getValue());+ assertEquals("tester", denial.user());+ assertEquals(+ NameIdentifierUtil.ofSchema("metalake", "catalog", "schema"), denial.identifier());+ assertEquals("canAccessMetadata", denial.methodName());+ assertEquals(CAN_ACCESS_METADATA, denial.expression());+ assertEquals(EventSource.GRAVITINO_ICEBERG_REST_SERVER, denial.eventSource());+ }+ }++ @Test+ public void testUserValidationDenialIsRecordedAgainstTheMetalake() throws Throwable {+ authorizationUtils+ .when(+ () ->+ AuthorizationUtils.checkCurrentUser(+ eq("metalake"), eq("tester"), any(AuthorizationRequestContext.class)))+ .thenThrow(new ForbiddenException("not a metalake user"));+ EventBus eventBus = mock(EventBus.class);+ try (MockedStatic<GravitinoEnv> envStatic = mockGravitinoEnv(eventBus)) {+ TestInterceptor interceptor = new TestInterceptor(Entity.EntityType.SCHEMA);+ interceptor.denialEventSource = Optional.of(EventSource.GRAVITINO_ICEBERG_REST_SERVER);++ interceptor.invoke(invocation("canAccessMetadata", "authorized"));++ ArgumentCaptor<BaseEvent> event = ArgumentCaptor.forClass(BaseEvent.class);+ verify(eventBus).dispatchEvent(event.capture());+ assertEquals(+ NameIdentifierUtil.ofMetalake("metalake"),+ assertInstanceOf(AuthorizationDenialFailureEvent.class, event.getValue()).identifier());+ }+ }++ @Test+ public void testNoDenialEventWithoutEventSourceOrForOtherFailures() throws Throwable {+ EventBus eventBus = mock(EventBus.class);+ try (MockedStatic<GravitinoEnv> envStatic = mockGravitinoEnv(eventBus)) {+ new TestInterceptor(Entity.EntityType.SCHEMA)+ .invoke(invocation("canAccessMetadata", "authorized"));++ TestInterceptor failing = new TestInterceptor(Entity.EntityType.SCHEMA);+ failing.denialEventSource = Optional.of(EventSource.GRAVITINO_ICEBERG_REST_SERVER);+ failing.resolutionFailure = new IllegalStateException("resolver failed");+ failing.invoke(invocation("canAccessMetadata", "authorized"));++ verify(eventBus, never()).dispatchEvent(any());+ }+ }++ private static MockedStatic<GravitinoEnv> mockGravitinoEnv(EventBus eventBus) {+ MockedStatic<GravitinoEnv> envStatic = mockStatic(GravitinoEnv.class);+ GravitinoEnv env = mock(GravitinoEnv.class);+ envStatic.when(GravitinoEnv::getInstance).thenReturn(env);+ when(env.eventBus()).thenReturn(eventBus);+ return envStatic;+ }+@Testpublic void testUnheldActiveRoleUsesProtocolMapper() throws Throwable {principal = principal.withActiveRoles(ActiveRoles.of(List.of("admin")));@@ -462,6 +538,7 @@ public class TestBaseMetadataAuthorizationMethodInterceptor {private boolean includeMetalake = true;private boolean skipAuthorization;private boolean skipExpressionEvaluation;+ private Optional<EventSource> denialEventSource = Optional.empty();private TestInterceptor(Entity.EntityType targetType) {this.targetType = targetType;@@ -495,6 +572,11 @@ public class TestBaseMetadataAuthorizationMethodInterceptor {return throwable;}+ @Override+ protected Optional<EventSource> authorizationDenialEventSource() {+ return denialEventSource;+ }+@Overrideprotected Optional<AuthorizationHandler> createAuthorizationHandler(Method method, Parameter[] parameters, Object[] args) {