Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14765] fix(iceberg): validate requests and record load authorization denials (#14766)

roryqi4c419787fdff
diff --git a/api/src/main/java/org/apache/gravitino/stats/Statistic.java b/api/src/main/java/org/apache/gravitino/stats/Statistic.java
index c7e5f64aba..50fc811fd7 100644
--- a/api/src/main/java/org/apache/gravitino/stats/Statistic.java
+++ b/api/src/main/java/org/apache/gravitino/stats/Statistic.java
@@ -53,9 +53,10 @@ public interface Statistic extends Auditable {
/**
* The statistic is predefined by Gravitino if the value is true. The statistic is defined by
- * users if the value is false. For example, the statistic "row_count" is a reserved statistic, A
- * custom statistic name must start with "custom." prefix to avoid name conflict with reserved
- * statistics. Because Gravitino may add more reserved statistics in the future.
+ * users if the value is false. For example, the statistic "row_count" is a reserved statistic. A
+ * custom statistic name must start with {@link #CUSTOM_PREFIX} to avoid conflicts with statistics
+ * that Gravitino may reserve in the future. Statistic names must not exceed {@link
+ * #MAX_NAME_LENGTH} characters, including the prefix.
*
* @return The type of the statistic.
*/
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
index c2deb469bb..c21f613ca8 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
@@ -74,6 +74,7 @@ import org.apache.gravitino.utils.MapUtils;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.exceptions.BadRequestException;
import org.apache.iceberg.exceptions.NamespaceNotEmptyException;
import org.apache.iceberg.exceptions.NoSuchNamespaceException;
import org.apache.iceberg.exceptions.RESTException;
@@ -628,7 +629,7 @@ public class IcebergCatalogOperations
return createdTable;
} catch (AlreadyExistsException e) {
throw new TableAlreadyExistsException(e, "Table already exists: %s", tableIdent.name());
- } catch (ValidationException e) {
+ } catch (ValidationException | BadRequestException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergTableValidation.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergTableValidation.java
index ec1075479a..509bd8e97d 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergTableValidation.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergTableValidation.java
@@ -155,6 +155,55 @@ class TestIcebergTableValidation {
.toArray(String[]::new));
}
+ @Test
+ void testMultipleSingleFieldBucketTransformsArePreserved() {
+ create(
+ "multiple_buckets",
+ new Column[] {
+ Column.of("a", Types.IntegerType.get()), Column.of("b", Types.StringType.get())
+ },
+ Transforms.bucket(16, new String[] {"a"}),
+ Transforms.bucket(8, new String[] {"b"}));
+ Transform[] partitioning = operations.loadTable(table("multiple_buckets")).partitioning();
+ assertEquals(2, partitioning.length);
+ assertEquals(Transforms.bucket(16, new String[] {"a"}), partitioning[0]);
+ assertEquals(Transforms.bucket(8, new String[] {"b"}), partitioning[1]);
+ }
+
+ @ParameterizedTest
+ @MethodSource("versionThreeTypes")
+ void testVersionThreeTypeWithVersionTwoIsBadRequest(Type type) {
+ Exception failure =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> create("unsupported_type", new Column[] {Column.of("value", type)}));
+ assertEquals(400, tableError(OperationType.CREATE, failure));
+ assertFalse(operations.tableExists(table("unsupported_type")));
+ }
+
+ @ParameterizedTest
+ @MethodSource("versionThreeTypes")
+ void testVersionThreeTypeRoundTrip(Type type) {
+ operations.createTable(
+ table("version_three"),
+ new Column[] {Column.of("value", type)},
+ "",
+ Map.of("format-version", "3"),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ new Index[0]);
+ assertEquals(type, operations.loadTable(table("version_three")).columns()[0].dataType());
+ }
+
+ private static Stream<Type> versionThreeTypes() {
+ return Stream.of(
+ Types.NullType.get(),
+ Types.VariantType.get(),
+ Types.GeometryType.of("OGC:CRS84"),
+ Types.GeographyType.of("OGC:CRS84", "spherical"));
+ }
+
private static Stream<Arguments> incompatiblePartitionTransforms() {
return Stream.of(
Arguments.of(Types.StringType.get(), Transforms.year("value")),
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java
index 70a6b574c0..9bd4c4ebf9 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java
@@ -177,6 +177,21 @@ public class TestCatalogNormalizeDispatcher {
}
}
+ @Test
+ void testRenameCatalogRejectsDottedName() {
+ NameIdentifier ident = NameIdentifier.of(metalake, "catalog");
+ Mockito.clearInvocations(catalogManager);
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ catalogNormalizeDispatcher.alterCatalog(
+ ident, CatalogChange.rename("catalog.xxx")));
+ Assertions.assertEquals("The catalog name 'catalog.xxx' is illegal.", exception.getMessage());
+ Mockito.verify(catalogManager, Mockito.never())
+ .alterCatalog(Mockito.eq(ident), Mockito.any(CatalogChange[].class));
+ }
+
@Test
void testConnectionChangesValidateRenamedCatalogName() {
NameIdentifier catalogIdent = NameIdentifier.of(metalake, "catalog");
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetadataObjectService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetadataObjectService.java
index 2728a1ee2b..f077a9641a 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetadataObjectService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetadataObjectService.java
@@ -36,6 +36,9 @@ import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.SecurableObjects;
import org.apache.gravitino.function.FunctionDefinition;
import org.apache.gravitino.function.FunctionDefinitions;
import org.apache.gravitino.function.FunctionImpl;
@@ -48,6 +51,8 @@ import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.JobTemplateEntity;
import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.policy.PolicyContent;
@@ -374,6 +379,75 @@ public class TestMetadataObjectService extends TestJDBCBackend {
assertTrue(metadataObjects.isEmpty());
}
+ /** Verifies that function grants resolve both renamed parents from their stable IDs. */
+ @TestTemplate
+ public void testFunctionPrivilegeSurvivesParentRenames() throws IOException {
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "function_catalog");
+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, catalog.name(), "function_schema");
+ FunctionEntity function =
+ createAndInsertFunctionEntity(
+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()), "function");
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("function_role")
+ .withNamespace(AuthorizationUtils.ofRoleNamespace(METALAKE_NAME))
+ .withProperties(Map.of())
+ .withAuditInfo(AUDIT_INFO)
+ .withSecurableObjects(
+ List.of(
+ SecurableObjects.parse(
+ "function_catalog.function_schema.function",
+ MetadataObject.Type.FUNCTION,
+ List.of(Privileges.ExecuteFunction.allow()))))
+ .build();
+ backend.insert(role, false);
+ RoleEntity loaded = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE);
+ assertEquals(
+ "function_catalog.function_schema.function", loaded.securableObjects().get(0).fullName());
+
+ backend.update(
+ catalog.nameIdentifier(),
+ Entity.EntityType.CATALOG,
+ e ->
+ CatalogEntity.builder()
+ .withId(catalog.id())
+ .withName("renamed_catalog")
+ .withNamespace(catalog.namespace())
+ .withType(catalog.getType())
+ .withProvider(catalog.getProvider())
+ .withComment(catalog.getComment())
+ .withProperties(catalog.getProperties())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ loaded = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE);
+ assertEquals(
+ "renamed_catalog.function_schema.function", loaded.securableObjects().get(0).fullName());
+
+ backend.update(
+ NameIdentifier.of(METALAKE_NAME, "renamed_catalog", schema.name()),
+ Entity.EntityType.SCHEMA,
+ e ->
+ SchemaEntity.builder()
+ .withId(schema.id())
+ .withName("renamed_schema")
+ .withNamespace(Namespace.of(METALAKE_NAME, "renamed_catalog"))
+ .withComment(schema.comment())
+ .withProperties(schema.properties())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ loaded = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE);
+ assertEquals(
+ "renamed_catalog.renamed_schema.function", loaded.securableObjects().get(0).fullName());
+ assertEquals(
+ List.of(Privileges.ExecuteFunction.allow()), loaded.securableObjects().get(0).privileges());
+ assertEquals(
+ function.id(),
+ EntityIdService.getEntityId(
+ NameIdentifier.of(METALAKE_NAME, "renamed_catalog", "renamed_schema", "function"),
+ Entity.EntityType.FUNCTION));
+ }
+
private FunctionEntity createAndInsertFunctionEntity(Namespace namespace, String functionName)
throws IOException {
FunctionEntity functionEntity =
diff --git a/docs/manage-statistics-in-gravitino.md b/docs/manage-statistics-in-gravitino.md
index 754915ae77..ac7b916aaf 100644
--- a/docs/manage-statistics-in-gravitino.md
+++ b/docs/manage-statistics-in-gravitino.md
@@ -14,7 +14,7 @@ This page covers the Gravitino API for statistics. For what a statistic is, the
reserved and custom, and how partition statistics relate to partitions, see
[Statistics](./statistics.md).
-Statistics attach to tables. Custom names must begin with `custom.` to stay clear of names Gravitino
+Statistics attach to tables. Custom names must begin with `custom-` to stay clear of names Gravitino
may reserve later.
## Table Statistics
@@ -44,8 +44,8 @@ maintenance job can therefore fail on a conflict under its existing failure hand
curl -X PUT -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" -d '{
"updates": {
- "custom.last_reviewed": "2026-08-02",
- "custom.owner_team": "risk"
+ "custom-last_reviewed": "2026-08-02",
+ "custom-owner_team": "risk"
}
}' http://localhost:8090/api/metalakes/example/objects/table/sales.public.orders/statistics
```
@@ -56,8 +56,8 @@ curl -X PUT -H "Accept: application/vnd.gravitino.v1+json" \
```java
Table orders = ...
Map<String, StatisticValue<?>> updates = Maps.newHashMap();
-updates.put("custom.last_reviewed", StatisticValues.stringValue("2026-08-02"));
-updates.put("custom.owner_team", StatisticValues.stringValue("risk"));
+updates.put("custom-last_reviewed", StatisticValues.stringValue("2026-08-02"));
+updates.put("custom-owner_team", StatisticValues.stringValue("risk"));
orders.supportsStatistics().updateStatistics(updates);
```
@@ -98,7 +98,7 @@ deleted or replaced while dropping existing statistics, the request fails with H
```shell
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" -d '{
- "names": ["custom.owner_team"]
+ "names": ["custom-owner_team"]
}' http://localhost:8090/api/metalakes/example/objects/table/sales.public.orders/statistics
```
@@ -106,7 +106,7 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
<TabItem value="java" label="Java">
```java
-orders.supportsStatistics().dropStatistics(ImmutableList.of("custom.owner_team"));
+orders.supportsStatistics().dropStatistics(ImmutableList.of("custom-owner_team"));
```
</TabItem>
@@ -129,7 +129,7 @@ curl -X PUT -H "Accept: application/vnd.gravitino.v1+json" \
"updates": [
{
"partitionName": "dt=2026-08-02",
- "statistics": {"custom.row_estimate": "18000"}
+ "statistics": {"custom-row_estimate": "18000"}
}
]
}' http://localhost:8090/api/metalakes/example/objects/table/sales.public.orders/statistics/partitions
@@ -140,7 +140,7 @@ curl -X PUT -H "Accept: application/vnd.gravitino.v1+json" \
```java
Map<String, StatisticValue<?>> stats = Maps.newHashMap();
-stats.put("custom.row_estimate", StatisticValues.longValue(18000L));
+stats.put("custom-row_estimate", StatisticValues.longValue(18000L));
orders.supportsPartitionStatistics().updatePartitionStatistics(
ImmutableList.of(PartitionStatisticsModification.update("dt=2026-08-02", stats)));
@@ -185,7 +185,7 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
"drops": [
{
"partitionName": "dt=2026-08-02",
- "statisticNames": ["custom.row_estimate"]
+ "statisticNames": ["custom-row_estimate"]
}
]
}' http://localhost:8090/api/metalakes/example/objects/table/sales.public.orders/statistics/partitions
@@ -198,7 +198,7 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
orders.supportsPartitionStatistics().dropPartitionStatistics(
ImmutableList.of(
PartitionStatisticsModification.drop(
- "dt=2026-08-02", ImmutableList.of("custom.row_estimate"))));
+ "dt=2026-08-02", ImmutableList.of("custom-row_estimate"))));
```
</TabItem>
diff --git a/docs/partitions.md b/docs/partitions.md
index 1195b9226d..b9816a51b0 100644
--- a/docs/partitions.md
+++ b/docs/partitions.md
@@ -62,8 +62,9 @@ arrives, which Iceberg calls hidden partitioning. There is no partition object t
which is why Iceberg is not in the list above.
Gravitino sets the spec when it creates the table. Identity, bucket, truncate, year, month, day, and
-hour transforms all convert to an Iceberg spec, with bucket limited to one field. List and range
-partitioning have no Iceberg equivalent and are rejected.
+hour transforms all convert to an Iceberg spec. Each bucket transform takes one field; a spec may
+contain multiple bucket transforms on different fields. List and range partitioning have no Iceberg
+equivalent and are rejected.
After creation, partitioning is changed through the engine rather than through the Gravitino API.
Point Spark, Trino, or another Iceberg client at the Iceberg REST catalog service, which listens on
diff --git a/docs/statistics.md b/docs/statistics.md
index b9d5ff18f7..7482ead019 100644
--- a/docs/statistics.md
+++ b/docs/statistics.md
@@ -33,8 +33,8 @@ you choose.
A reserved statistic is one Gravitino defines, such as `row_count`. The set can grow in future
releases, so reserved names are not available for your own use.
-A custom statistic is yours, and its name must begin with `custom.` to keep it clear of anything
-Gravitino may reserve later. The prefix is the only naming rule.
+A custom statistic is yours, and its name must begin with `custom-` to keep it clear of anything
+Gravitino may reserve later. Statistic names must not exceed 128 characters, including the prefix.
### Modifiable and Not
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
index f062286287..ce7313497e 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
@@ -51,6 +51,7 @@ import org.apache.iceberg.TableMetadataParser;
import org.apache.iceberg.TableOperations;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.Transaction;
+import org.apache.iceberg.aws.s3.S3FileIO;
import org.apache.iceberg.catalog.Catalog;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.SupportsNamespaces;
@@ -240,6 +241,7 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
public LoadTableResponse registerTable(Namespace namespace, RegisterTableRequest request) {
+ validateTableLocation(request.metadataLocation());
try {
return CatalogHandlers.registerTable(getCatalog(), namespace, request);
} catch (NotFoundException e) {
@@ -265,6 +267,7 @@ public class IcebergCatalogWrapper implements AutoCloseable {
public LoadTableResponse createTable(Namespace namespace, CreateTableRequest request) {
request.validate();
validateTableDefinition(request);
+ validateTableLocation(request.location());
Catalog loadedCatalog = getCatalog();
LoadTableResponse loadTableResponse;
try {
@@ -343,6 +346,7 @@ public class IcebergCatalogWrapper implements AutoCloseable {
* @throws BadRequestException if no metadata file exists at the location
*/
public TableMetadata loadTableMetadataFromLocation(String metadataLocation) {
+ validateTableLocation(metadataLocation);
try (FileIO fileIO = CatalogUtil.loadFileIO(fileIOImpl(), fileIOProperties(), null)) {
return TableMetadataParser.read(fileIO, metadataLocation);
} catch (NotFoundException e) {
@@ -432,6 +436,11 @@ public class IcebergCatalogWrapper implements AutoCloseable {
public LoadTableResponse updateTable(
TableIdentifier tableIdentifier, UpdateTableRequest updateTableRequest) {
+ for (MetadataUpdate update : updateTableRequest.updates()) {
+ if (update instanceof MetadataUpdate.SetLocation) {
+ validateTableLocation(((MetadataUpdate.SetLocation) update).location());
+ }
+ }
getMetadataCache().invalidate(tableIdentifier);
validateDefaultSpecAndSortOrder(tableIdentifier, updateTableRequest);
LoadTableResponse loadTableResponse;
@@ -637,6 +646,19 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
}
+ private void validateTableLocation(@Nullable String location) {
+ if (location == null || !S3FileIO.class.getName().equals(fileIOImpl())) {
+ return;
+ }
+ String[] parts = location.split("://", 2);
+ if (parts.length != 2
+ || !Set.of("s3", "s3a", "s3n").contains(parts[0])
+ || parts[1].split("/", 2)[0].isBlank()) {
+ throw new BadRequestException(
+ "Invalid table location '%s': this catalog requires an S3 location", location);
+ }
+ }
+
/**
* Rejects set-default-spec and set-default-sort-order updates naming an id the table does not
* have; Iceberg applies them unchecked and then fails with a NullPointerException.
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
index ca0122231b..ffa08e81ec 100644
--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
@@ -72,6 +72,112 @@ import org.mockito.Mockito;
public class TestIcebergCatalogWrapper {
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/table", "gs://bucket/table", "/tmp/table", "s3:///table"})
+ void testS3CatalogRejectsInvalidLocationBeforeCreatingTable(String location) {
+ IcebergCatalogWrapper wrapper =
+ Mockito.spy(new IcebergCatalogWrapper(new IcebergConfig(unreachableConfig())));
+ Mockito.doReturn("org.apache.iceberg.aws.s3.S3FileIO").when(wrapper).fileIOImpl();
+ for (boolean staged : new boolean[] {false, true}) {
+ CreateTableRequest.Builder builder =
+ CreateTableRequest.builder()
+ .withName("invalid_location")
+ .withSchema(new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())))
+ .withLocation(location);
+ if (staged) {
+ builder.stageCreate();
+ }
+ CreateTableRequest request = builder.build();
+ BadRequestException failure =
+ Assertions.assertThrows(
+ BadRequestException.class, () -> wrapper.createTable(Namespace.of("s"), request));
+ Assertions.assertTrue(failure.getMessage().contains(location));
+ }
+ Mockito.verify(wrapper, Mockito.never()).getCatalog();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/table", "gs://bucket/table", "/tmp/table", "s3:///table"})
+ void testS3CatalogRejectsInvalidRegisterAndUpdateLocations(String location) {
+ IcebergCatalogWrapper wrapper =
+ Mockito.spy(new IcebergCatalogWrapper(new IcebergConfig(unreachableConfig())));
+ Mockito.doReturn("org.apache.iceberg.aws.s3.S3FileIO").when(wrapper).fileIOImpl();
+ RegisterTableRequest register =
+ ImmutableRegisterTableRequest.builder().name("t").metadataLocation(location).build();
+ UpdateTableRequest update =
+ new UpdateTableRequest(
+ Collections.emptyList(),
+ Collections.singletonList(new MetadataUpdate.SetLocation(location)));
+
+ BadRequestException registerFailure =
+ Assertions.assertThrows(
+ BadRequestException.class, () -> wrapper.registerTable(Namespace.of("s"), register));
+ Assertions.assertTrue(registerFailure.getMessage().contains(location));
+ BadRequestException metadataFailure =
+ Assertions.assertThrows(
+ BadRequestException.class, () -> wrapper.loadTableMetadataFromLocation(location));
+ Assertions.assertTrue(metadataFailure.getMessage().contains(location));
+ BadRequestException updateFailure =
+ Assertions.assertThrows(
+ BadRequestException.class,
+ () -> wrapper.updateTable(TableIdentifier.of("s", "t"), update));
+ Assertions.assertTrue(updateFailure.getMessage().contains(location));
+ Mockito.verify(wrapper, Mockito.never()).getCatalog();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"s3://bucket/table", "s3a://bucket/table", "s3n://bucket/table"})
+ void testS3CatalogAcceptsRegisterAndUpdateLocationSchemes(String location) {
+ IcebergCatalogWrapper wrapper =
+ Mockito.spy(new IcebergCatalogWrapper(new IcebergConfig(unreachableConfig())));
+ Mockito.doReturn("org.apache.iceberg.aws.s3.S3FileIO").when(wrapper).fileIOImpl();
+ Catalog catalog = Mockito.mock(Catalog.class);
+ Mockito.doReturn(catalog).when(wrapper).getCatalog();
+ Mockito.when(catalog.registerTable(Mockito.any(), Mockito.eq(location), Mockito.anyBoolean()))
+ .thenThrow(new IllegalStateException("register backend reached"));
+ Mockito.when(catalog.loadTable(Mockito.any()))
+ .thenThrow(new IllegalStateException("update backend reached"));
+ RegisterTableRequest register =
+ ImmutableRegisterTableRequest.builder().name("t").metadataLocation(location).build();
+ UpdateTableRequest update =
+ new UpdateTableRequest(
+ Collections.emptyList(),
+ Collections.singletonList(new MetadataUpdate.SetLocation(location)));
+
+ IllegalStateException registerFailure =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> wrapper.registerTable(Namespace.of("s"), register));
+ Assertions.assertEquals("register backend reached", registerFailure.getMessage());
+ IllegalStateException updateFailure =
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> wrapper.updateTable(TableIdentifier.of("s", "t"), update));
+ Assertions.assertEquals("update backend reached", updateFailure.getMessage());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"s3://bucket/table", "s3a://bucket/table", "s3n://bucket/table"})
+ void testS3CatalogAcceptsSupportedLocationSchemes(String location) {
+ IcebergCatalogWrapper wrapper =
+ Mockito.spy(new IcebergCatalogWrapper(new IcebergConfig(unreachableConfig())));
+ Mockito.doReturn("org.apache.iceberg.aws.s3.S3FileIO").when(wrapper).fileIOImpl();
+ Catalog catalog = Mockito.mock(Catalog.class);
+ Mockito.doReturn(catalog).when(wrapper).getCatalog();
+ CreateTableRequest request =
+ CreateTableRequest.builder()
+ .withName("valid_location")
+ .withSchema(new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())))
+ .withLocation(location)
+ .build();
+ // Stop after validation, before the mocked backend creates anything.
+ Mockito.when(catalog.buildTable(Mockito.any(), Mockito.any()))
+ .thenThrow(new IllegalStateException("backend reached"));
+ IllegalStateException failure =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> wrapper.createTable(Namespace.of("s"), request));
+ Assertions.assertEquals("backend reached", failure.getMessage());
+ }
+
@Test
void testLoadViewReportsMissingAfterNativeRename(@TempDir Path warehouseDir) throws Exception {
Namespace namespace = Namespace.of("views");
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java
index 5623f3b879..4f0dc559f4 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateNamespaceAuthzHandler.java
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.Map;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;
import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;
@@ -31,7 +32,6 @@ import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.exceptions.BadRequestException;
-import org.apache.iceberg.exceptions.ForbiddenException;
import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
/**
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.java
index df426feb68..4d3327c57a 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
@@ -28,6 +28,8 @@ import java.util.function.Supplier;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
@@ -35,10 +37,12 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationExpres
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;
import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata.RequestType;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.catalog.Namespace;
-import org.apache.iceberg.exceptions.ForbiddenException;
+import org.apache.iceberg.exceptions.BadRequestException;
+import org.apache.iceberg.exceptions.NoSuchNamespaceException;
import org.apache.iceberg.rest.RESTUtil;
/** Shared helper for Iceberg load table/view authorization handlers. */
@@ -84,10 +88,25 @@ final class IcebergLoadAuthzHandlerHelper {
return new LoadContext(catalogId.namespace().level(0), catalogId.name(), schemaId.name());
}
- static IcebergCatalogWrapper getCatalogWrapper(String catalog) {
- return IcebergRESTServerContext.getInstance()
- .catalogWrapperManager()
- .getCatalogWrapper(catalog);
+ static IcebergCatalogWrapper getCatalogWrapper(
+ String catalog, Map<EntityType, NameIdentifier> nameIdentifierMap) {
+ try {
+ return IcebergRESTServerContext.getInstance()
+ .catalogWrapperManager()
+ .getCatalogWrapper(catalog);
+ } catch (NoSuchCatalogException | IllegalArgumentException e) {
+ // A load handler resolves the backend before evaluating table/view privileges. Do not
+ // disclose catalog existence or its provider to a caller who cannot see the catalog.
+ if (!isAllowed(
+ nameIdentifierMap,
+ AuthorizationExpressionConstants.LOAD_CATALOG_AUTHORIZATION_EXPRESSION)) {
+ throw new ForbiddenException("Not authorized to access catalog '%s'", catalog);
+ }
+ if (e instanceof NoSuchCatalogException) {
+ throw new NoSuchNamespaceException(e, "No Iceberg configuration for catalog '%s'", catalog);
+ }
+ throw new BadRequestException(e, "%s", e.getMessage());
+ }
}
static String resolveExpression(
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.java
index 9689b2de12..756c64b2a3 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
@@ -45,6 +45,7 @@ import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizatio
import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.exceptions.BadRequestException;
import org.apache.iceberg.rest.RESTUtil;
/**
@@ -89,8 +90,15 @@ public class IcebergMetadataAuthorizationMethodInterceptor
Parameter parameter = parameters[i];
AuthorizationMetadata authorizeResource =
parameter.getAnnotation(AuthorizationMetadata.class);
- if (authorizeResource != null) {
- Entity.EntityType type = authorizeResource.type();
+ IcebergAuthorizationMetadata icebergResource =
+ parameter.getAnnotation(IcebergAuthorizationMetadata.class);
+ EntityType type =
+ authorizeResource != null
+ ? authorizeResource.type()
+ : icebergResource != null && icebergResource.type() == RequestType.LOAD_TABLE
+ ? EntityType.TABLE
+ : null;
+ if (type != null) {
String value = String.valueOf(args[i]);
switch (type) {
case CATALOG:
@@ -99,6 +107,11 @@ public class IcebergMetadataAuthorizationMethodInterceptor
StringUtils.isBlank(value) || value.endsWith("/")
? IcebergRESTUtils.getCatalogName(value)
: value;
+ if (catalog.contains(".")) {
+ // CatalogNormalizeDispatcher rejects dots when creating or renaming catalogs.
+ throw new BadRequestException(
+ "Invalid catalog prefix '%s': use a catalog name without '.'", catalog);
+ }
nameIdentifierMap.put(
Entity.EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalakeName, catalog));
break;
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.java
index 6b72ea2c0d..707e4c28fe 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
@@ -88,7 +88,7 @@ public class LoadTableAuthzHandler implements AuthorizationHandler {
// 1. Authorize the table access (see performTableAuthorization) -> 403 if unauthorized
// 2. Let request proceed - the actual loadTable() call will handle non-existence
IcebergCatalogWrapper catalogWrapper =
- IcebergLoadAuthzHandlerHelper.getCatalogWrapper(loadContext.catalog());
+ IcebergLoadAuthzHandlerHelper.getCatalogWrapper(loadContext.catalog(), nameIdentifierMap);
// Validate that this is not a metadata table access
if (isMetadataTable(tableName, namespace, catalogWrapper)) {
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadViewAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadViewAuthzHandler.java
index ec0b9bbf64..8cc06fc73e 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadViewAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/LoadViewAuthzHandler.java
@@ -74,7 +74,7 @@ public class LoadViewAuthzHandler implements AuthorizationHandler {
"Missing catalog or schema context for view authorization"));
IcebergCatalogWrapper catalogWrapper =
- IcebergLoadAuthzHandlerHelper.getCatalogWrapper(loadContext.catalog());
+ IcebergLoadAuthzHandlerHelper.getCatalogWrapper(loadContext.catalog(), nameIdentifierMap);
TableIdentifier viewIdentifier = TableIdentifier.of(namespace, viewName);
NameIdentifier viewId =
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java
index 9839c920a5..6fb6023c60 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameTableAuthzHandler.java
@@ -28,6 +28,7 @@ import java.util.Optional;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;
@@ -35,7 +36,6 @@ import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.exceptions.BadRequestException;
-import org.apache.iceberg.exceptions.ForbiddenException;
import org.apache.iceberg.rest.requests.RenameTableRequest;
/**
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java
index d5996b810f..8939980689 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RenameViewAuthzHandler.java
@@ -26,6 +26,7 @@ import java.util.Optional;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.server.authorization.annotations.IcebergAuthorizationMetadata;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
@@ -34,7 +35,6 @@ import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.exceptions.BadRequestException;
-import org.apache.iceberg.exceptions.ForbiddenException;
import org.apache.iceberg.rest.requests.RenameTableRequest;
/**
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthorizationAudit.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthorizationAudit.java
new file mode 100644
index 0000000000..4616ebb983
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthorizationAudit.java
@@ -0,0 +1,286 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.filter;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.aopalliance.intercept.MethodInvocation;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.UserPrincipal;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
+import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
+import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
+import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
+import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;
+import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;
+import org.apache.gravitino.iceberg.service.rest.IcebergViewOperations;
+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.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.iceberg.exceptions.BadRequestException;
+import org.apache.iceberg.exceptions.ForbiddenException;
+import org.apache.iceberg.exceptions.NoSuchNamespaceException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+
+class TestIcebergLoadAuthorizationAudit {
+ private GravitinoAuthorizer authorizer;
+ private EventBus eventBus;
+ private IcebergCatalogWrapperManager wrapperManager;
+ private IcebergMetadataAuthorizationMethodInterceptor interceptor;
+ private MockedStatic<PrincipalUtils> principals;
+ private MockedStatic<AuthorizationUtils> authorization;
+ private MockedStatic<GravitinoAuthorizerProvider> providers;
+ private MockedStatic<GravitinoEnv> environments;
+
+ @BeforeEach
+ void setUp() {
+ IcebergConfigProvider configProvider = mock(IcebergConfigProvider.class);
+ when(configProvider.getMetalakeName()).thenReturn("ml");
+ when(configProvider.getDefaultCatalogName()).thenReturn("cat");
+ wrapperManager = mock(IcebergCatalogWrapperManager.class);
+ when(wrapperManager.getCatalogWrapper("cat")).thenReturn(mock(CatalogWrapperForREST.class));
+ IcebergRESTServerContext.create(configProvider, false, false, true, wrapperManager);
+
+ authorizer = mock(GravitinoAuthorizer.class);
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+ providers = mockStatic(GravitinoAuthorizerProvider.class);
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ principals = mockStatic(PrincipalUtils.class);
+ principals.when(PrincipalUtils::getCurrentPrincipal).thenReturn(new UserPrincipal("reader"));
+ principals.when(PrincipalUtils::getCurrentUserName).thenReturn("reader");
+ authorization = mockStatic(AuthorizationUtils.class);
+
+ eventBus = mock(EventBus.class);
+ GravitinoEnv env = mock(GravitinoEnv.class);
+ when(env.eventBus()).thenReturn(eventBus);
+ environments = mockStatic(GravitinoEnv.class);
+ environments.when(GravitinoEnv::getInstance).thenReturn(env);
+ interceptor = new IcebergMetadataAuthorizationMethodInterceptor();
+ }
+
+ @AfterEach
+ void tearDown() {
+ environments.close();
+ authorization.close();
+ principals.close();
+ providers.close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"loadTable", "loadView"})
+ void testLoadDenialRecordsObjectAndExpression(String operation) throws Throwable {
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(403, response.getStatus());
+ assertEquals("ForbiddenException", ((ErrorResponse) response.getEntity()).type());
+ }
+ ArgumentCaptor<BaseEvent> event = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(event.capture());
+ AuthorizationDenialFailureEvent denial =
+ assertInstanceOf(AuthorizationDenialFailureEvent.class, event.getValue());
+ assertEquals("reader", denial.user());
+ assertEquals(NameIdentifier.of("ml", "cat", "s", "object"), denial.identifier());
+ assertEquals(operation, denial.methodName());
+ assertEquals(EventSource.GRAVITINO_ICEBERG_REST_SERVER, denial.eventSource());
+ assertEquals(
+ invocation.getMethod().getAnnotation(AuthorizationExpression.class).expression(),
+ denial.expression());
+ verify(invocation, never()).proceed();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"loadTable", "loadView"})
+ void testAllowedLoadDoesNotRecordDenial(String operation) throws Throwable {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(true);
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ when(invocation.proceed()).thenReturn("loaded");
+ assertEquals("loaded", interceptor.invoke(invocation));
+ verify(eventBus, never()).dispatchEvent(any());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"loadTable", "loadView"})
+ void testBackendForbiddenDuringAuthorizationDoesNotRecordDenial(String operation)
+ throws Throwable {
+ when(wrapperManager.getCatalogWrapper("cat"))
+ .thenThrow(new ForbiddenException("Backend credentials rejected"));
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(403, response.getStatus());
+ assertEquals(
+ "Backend credentials rejected", ((ErrorResponse) response.getEntity()).message());
+ }
+ verify(eventBus, never()).dispatchEvent(any());
+ verify(invocation, never()).proceed();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"loadTable", "loadView"})
+ void testBackendForbiddenAfterAuthorizationDoesNotRecordDenial(String operation)
+ throws Throwable {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(true);
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ when(invocation.proceed()).thenThrow(new ForbiddenException("Backend credentials rejected"));
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(403, response.getStatus());
+ assertEquals(
+ "Backend credentials rejected", ((ErrorResponse) response.getEntity()).message());
+ }
+ verify(eventBus, never()).dispatchEvent(any());
+ verify(invocation).proceed();
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "loadTable,false,403",
+ "loadView,false,403",
+ "loadTable,true,400",
+ "loadView,true,400"
+ })
+ void testNonIcebergCatalogIsClientErrorOnlyForVisibleCatalog(
+ String operation, boolean owner, int status) throws Throwable {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(owner);
+ when(wrapperManager.getCatalogWrapper("cat"))
+ .thenThrow(new IllegalArgumentException("Catalog cat is not an Iceberg catalog"));
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(status, response.getStatus());
+ }
+ verify(invocation, never()).proceed();
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "loadTable,false,403",
+ "loadView,false,403",
+ "loadTable,true,404",
+ "loadView,true,404"
+ })
+ void testMissingCatalogDoesNotBecomeInternalError(String operation, boolean owner, int status)
+ throws Throwable {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(owner);
+ when(wrapperManager.getCatalogWrapper("cat"))
+ .thenThrow(new NoSuchCatalogException("Catalog cat does not exist"));
+ MethodInvocation invocation = loadInvocation(operation, "cat/");
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(status, response.getStatus());
+ ErrorResponse error = (ErrorResponse) response.getEntity();
+ assertEquals(owner ? "NoSuchNamespaceException" : "ForbiddenException", error.type());
+ assertEquals(
+ owner
+ ? "No Iceberg configuration for catalog 'cat'"
+ : "Not authorized to access catalog 'cat'",
+ error.message());
+ }
+ verify(invocation, never()).proceed();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testCatalogLookupFailurePreservesCause(boolean missing) {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(true);
+ RuntimeException cause =
+ missing
+ ? new NoSuchCatalogException("Catalog cat does not exist")
+ : new IllegalArgumentException("Catalog cat is not an Iceberg catalog");
+ when(wrapperManager.getCatalogWrapper("cat")).thenThrow(cause);
+ Class<? extends RuntimeException> expectedType =
+ missing ? NoSuchNamespaceException.class : BadRequestException.class;
+
+ RuntimeException failure =
+ assertThrows(
+ expectedType,
+ () ->
+ IcebergLoadAuthzHandlerHelper.getCatalogWrapper(
+ "cat",
+ Map.of(
+ EntityType.METALAKE, NameIdentifier.of("ml"),
+ EntityType.CATALOG, NameIdentifier.of("ml", "cat"))));
+
+ assertSame(cause, failure.getCause());
+ assertEquals(
+ missing ? "No Iceberg configuration for catalog 'cat'" : cause.getMessage(),
+ failure.getMessage());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"loadTable", "loadView"})
+ void testMalformedCatalogPrefixIsBadRequest(String operation) throws Throwable {
+ MethodInvocation invocation = loadInvocation(operation, "ml.cat/");
+ try (Response response = (Response) interceptor.invoke(invocation)) {
+ assertEquals(400, response.getStatus());
+ assertEquals("BadRequestException", ((ErrorResponse) response.getEntity()).type());
+ }
+ verify(wrapperManager, never()).getCatalogWrapper(any());
+ verify(eventBus, never()).dispatchEvent(any());
+ verify(invocation, never()).proceed();
+ }
+
+ private MethodInvocation loadInvocation(String operation, String prefix) throws Exception {
+ boolean table = operation.equals("loadTable");
+ Method method =
+ table
+ ? IcebergTableOperations.class.getMethod(
+ operation,
+ String.class,
+ String.class,
+ String.class,
+ String.class,
+ String.class,
+ String.class)
+ : IcebergViewOperations.class.getMethod(
+ operation, String.class, String.class, String.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(
+ table
+ ? new Object[] {prefix, "s", "object", "all", null, null}
+ : new Object[] {prefix, "s", "object"});
+ return invocation;
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthzHandlerHelper.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthzHandlerHelper.java
index f675986510..2601b1c0d7 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthzHandlerHelper.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestIcebergLoadAuthzHandlerHelper.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
@@ -45,7 +46,6 @@ import org.apache.gravitino.server.web.filter.IcebergLoadAuthzHandlerHelper.Load
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.catalog.Namespace;
-import org.apache.iceberg.exceptions.ForbiddenException;
import org.apache.iceberg.exceptions.NoSuchViewException;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
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.java
index ce94c9c250..ac4cd8aa8d 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
@@ -35,6 +35,7 @@ import java.util.Map;
import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
@@ -49,7 +50,6 @@ 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;
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.java
index 02b4686787..08600b4314 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
@@ -203,6 +203,16 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {
return false;
}
+ /**
+ * Identifies authorization denials, including a protocol's own forbidden exception.
+ *
+ * @param exception exception raised while authorizing the request
+ * @return whether the exception represents a denied request
+ */
+ protected boolean isAuthorizationDenial(Exception exception) {
+ return exception instanceof ForbiddenException;
+ }
+
/**
* Returns whether the complete local authorization pipeline should be skipped. This is intended
* for a protocol proxy whose downstream Gravitino server authorizes the same request.
@@ -387,10 +397,10 @@ public abstract class BaseMetadataAuthorizationMethodInterceptor {
}
}
} catch (Exception ex) {
- if (ex instanceof ForbiddenException) {
+ if (isAuthorizationDenial(ex)) {
dispatchAuthorizationDenial(deniedObject, method.getName(), deniedExpression);
}
- if (ex instanceof ForbiddenException || isExceptionPropagate(ex)) {
+ if (isAuthorizationDenial(ex) || isExceptionPropagate(ex)) {
return toErrorResponse(method, args, ex);
}
String currentUser = PrincipalUtils.getCurrentUserName();