This is an automated email from the ASF dual-hosted git repository.
roryqi pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/branch-1.3 by this push:
new 527fcaa553 [Cherry-pick to branch-1.3] [#14765] fix(iceberg): validate
requests and record load authorization denials (#14766) (#14795)
527fcaa553 is described below
commit 527fcaa5535bd734f767d7879986fa1172316b95
Author: github-actions[bot]
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Tue Nov 10 09:42:20 2026 +0800
[Cherry-pick to branch-1.3] [#14765] fix(iceberg): validate requests and
record load authorization denials (#14766) (#14795)
### What changes were proposed in this pull request?
Backport #14766 to `branch-1.3`: audit denied Iceberg loads with their
object/method/expression, validate catalog prefixes and S3 locations,
translate table-definition errors to HTTP 400, and correct the
statistics and bucket-transform documentation.
Resolve the namespace-handler import conflict while preserving
branch-1.3 namespace behavior. Use invalid-format-version regressions
for the BadRequest-to-400 conversion because the new v3 Gravitino type
APIs are only on main. Initialize and restore the lock-manager fixture
so the catalog-name tests run independently. Retain function-grant
coverage across parent catalog/schema renames.
### Why are the changes needed?
Denied loads can be audited as UNKNOWN, invalid requests can return
generic authorization or storage errors, and copied documentation
examples can fail validation.
Fixes #14765. Backport of #14766.
### Does this PR introduce _any_ user-facing change?
Yes. The load-denial audit, request-validation and documentation fixes
apply to branch-1.3. No new configuration keys or Gravitino type APIs.
### How was this patch tested?
- 104 focused tests passed with `-PskipITs` across
`iceberg-rest-server`, `iceberg-common`, `catalog-lakehouse-iceberg`,
`server-common` and `core` (including H2 function-grant parent renames).
No failures or skips.
- Scoped Spotless formatting/checks, `git diff --check`, and a
tracked-Java conflict-marker scan passed.
- Deployed HA, storage-service E2E and full repository suites were not
run.
---------
Co-authored-by: roryqi <[email protected]>
Co-authored-by: roryqi <[email protected]>
---
.../java/org/apache/gravitino/stats/Statistic.java | 7 +-
.../iceberg/IcebergCatalogOperations.java | 3 +-
.../iceberg/TestIcebergTableValidation.java | 37 +++
.../catalog/TestCatalogNormalizeDispatcher.java | 26 +-
.../service/TestMetadataObjectService.java | 74 ++++++
docs/manage-statistics-in-gravitino.md | 22 +-
docs/partitions.md | 5 +-
docs/statistics.md | 4 +-
.../iceberg/common/ops/IcebergCatalogWrapper.java | 22 ++
.../common/ops/TestIcebergCatalogWrapper.java | 106 ++++++++
.../web/filter/CreateNamespaceAuthzHandler.java | 2 +-
.../web/filter/IcebergLoadAuthzHandlerHelper.java | 29 ++-
...bergMetadataAuthorizationMethodInterceptor.java | 17 +-
.../server/web/filter/LoadTableAuthzHandler.java | 2 +-
.../server/web/filter/LoadViewAuthzHandler.java | 2 +-
.../server/web/filter/RenameTableAuthzHandler.java | 2 +-
.../server/web/filter/RenameViewAuthzHandler.java | 2 +-
.../filter/TestIcebergLoadAuthorizationAudit.java | 286 +++++++++++++++++++++
.../filter/TestIcebergLoadAuthzHandlerHelper.java | 2 +-
.../web/filter/TestLoadTableAuthzHandler.java | 2 +-
...BaseMetadataAuthorizationMethodInterceptor.java | 14 +-
21 files changed, 630 insertions(+), 36 deletions(-)
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 708edb4d8c..0f82b7d1c5 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
@@ -80,6 +80,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.ValidationException;
@@ -625,7 +626,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 282b3a32b2..71f8bb8735 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
@@ -54,6 +54,7 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
class TestIcebergTableValidation {
@@ -170,6 +171,42 @@ 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
+ @ValueSource(strings = {"0", "999", "not-a-version"})
+ void testInvalidFormatVersionIsBadRequest(String version) {
+ Exception failure =
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.createTable(
+ table("invalid_version"),
+ new Column[] {Column.of("value", Types.IntegerType.get())},
+ "",
+ Map.of("format-version", version),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ new Index[0]));
+ assertTrue(failure.getMessage().contains("format-version"));
+ assertEquals(400, tableError(OperationType.CREATE, failure));
+ assertFalse(operations.tableExists(table("invalid_version")));
+ }
+
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 9a0810b7db..551a703651 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogNormalizeDispatcher.java
@@ -27,13 +27,17 @@ import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.CatalogChange;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.lock.LockManager;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.SchemaVersion;
@@ -51,6 +55,7 @@ public class TestCatalogNormalizeDispatcher {
private static CatalogNormalizeDispatcher catalogNormalizeDispatcher;
private static CatalogManager catalogManager;
private static EntityStore entityStore;
+ @Nullable private static LockManager previousLockManager;
private static final String metalake = "metalake";
private static final BaseMetalake metalakeEntity =
BaseMetalake.builder()
@@ -62,7 +67,7 @@ public class TestCatalogNormalizeDispatcher {
.build();
@BeforeAll
- public static void setUp() throws IOException {
+ public static void setUp() throws IOException, IllegalAccessException {
Config config = new Config(false) {};
config.set(Configs.CATALOG_LOAD_ISOLATED, false);
@@ -71,6 +76,8 @@ public class TestCatalogNormalizeDispatcher {
entityStore.put(metalakeEntity, true);
+ previousLockManager = GravitinoEnv.getInstance().lockManager();
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new
LockManager(config), true);
catalogManager = new CatalogManager(config, entityStore, new
RandomIdGenerator());
catalogManager = Mockito.spy(catalogManager);
catalogNormalizeDispatcher = new
CatalogNormalizeDispatcher(catalogManager);
@@ -94,6 +101,8 @@ public class TestCatalogNormalizeDispatcher {
catalogManager.close();
catalogManager = null;
}
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager",
previousLockManager, true);
+ previousLockManager = null;
}
@Test
@@ -171,6 +180,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 2037c43b60..cb0bd858d0 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
@@ -31,8 +31,8 @@ maintained by the system are not modifiable and the request
is rejected.
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
```
@@ -43,8 +43,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);
```
@@ -80,7 +80,7 @@ List<Statistic> statistics =
orders.supportsStatistics().listStatistics();
```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
```
@@ -88,7 +88,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>
@@ -111,7 +111,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
@@ -122,7 +122,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)));
@@ -167,7 +167,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
@@ -180,7 +180,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 2a3c25106d..337eff0b8b 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 9a39703212..d1d959eeb1 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
@@ -54,6 +54,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;
@@ -237,6 +238,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) {
@@ -262,6 +264,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 {
@@ -340,6 +343,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) {
@@ -429,6 +433,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;
@@ -689,6 +698,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 8e7ff98bfe..b89328da5f 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
@@ -70,6 +70,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 32e34a1b0c..44644e03a3 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,13 +24,13 @@ 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.server.authorization.annotations.IcebergAuthorizationMetadata;
import
org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;
import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.exceptions.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 2980614e5a..b2fe19fbb1 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 a3b5efb86d..12ae97aa05 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
@@ -199,6 +199,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.
@@ -350,10 +360,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();