Skip to content

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

[#14995] fix(iceberg): authorize table locations and optimize registration lookup (#15004)

roryqi3d0b193fd260
diff --git a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
index 032cee8c2e..652de37e8f 100644
--- a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
+++ b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/integration/test/CatalogPostgreSqlIT.java
@@ -464,18 +464,15 @@ public class CatalogPostgreSqlIT extends BaseIT {
SupportsSchemas schemas = catalog.asSchemas();
String schemaName = RandomNameUtils.genRandomName("ct_db");
- // should throw an exception with string that might contain SQL injection
+ // Creation rejects SQL-looking names. Drops address existing native identifiers, so a
+ // nonexistent name within PostgreSQL's byte limit returns false instead of executing SQL.
String sqlInjection = schemaName + "; DROP TABLE important_table; -- ";
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
schemas.createSchema(sqlInjection, null, null);
});
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () -> {
- schemas.dropSchema(sqlInjection, false);
- });
+ Assertions.assertFalse(schemas.dropSchema(sqlInjection, false));
String sqlInjection1 = schemaName + "; SELECT pg_sleep(10);";
Assertions.assertThrows(
@@ -483,11 +480,7 @@ public class CatalogPostgreSqlIT extends BaseIT {
() -> {
schemas.createSchema(sqlInjection1, null, null);
});
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () -> {
- schemas.dropSchema(sqlInjection1, false);
- });
+ Assertions.assertFalse(schemas.dropSchema(sqlInjection1, false));
String sqlInjection2 =
schemaName + "`; UPDATE Users SET password = 'newpassword' WHERE username = 'admin'; -- ";
@@ -522,11 +515,29 @@ public class CatalogPostgreSqlIT extends BaseIT {
() -> {
schemas.createSchema(invalidInput2, null, null);
});
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () -> {
- schemas.dropSchema(invalidInput2, false);
- });
+ Assertions.assertFalse(schemas.dropSchema(invalidInput2, false));
+ }
+
+ @Test
+ void testDropNativeSchemaNameTreatsSqlAsIdentifier() {
+ SupportsSchemas schemas = catalog.asSchemas();
+ String survivor = RandomNameUtils.genRandomName("keep");
+ String nativeName = "native\"; DROP SCHEMA " + survivor + "; --";
+ String quotedName = "\"" + nativeName.replace("\"", "\"\"") + "\"";
+ schemas.createSchema(survivor, null, Collections.emptyMap());
+ try {
+ postgreSqlService.executeQuery("CREATE SCHEMA " + quotedName);
+ Assertions.assertEquals(nativeName, schemas.loadSchema(nativeName).name());
+ Assertions.assertTrue(schemas.dropSchema(nativeName, false));
+ Assertions.assertFalse(schemas.dropSchema(nativeName, false));
+ Assertions.assertEquals(survivor, schemas.loadSchema(survivor).name());
+ Assertions.assertThrows(
+ NoSuchSchemaException.class,
+ () -> postgreSqlService.loadSchema(NameIdentifier.of(nativeName)));
+ } finally {
+ postgreSqlService.executeQuery("DROP SCHEMA IF EXISTS " + quotedName);
+ schemas.dropSchema(survivor, false);
+ }
}
@Test
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
index b02a8a7919..3c218a0628 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
@@ -91,6 +91,29 @@ public class IcebergCatalogCapability implements Capability {
return Capability.super.specificationOnName(scope, name);
}
+ /**
+ * Accepts existing Iceberg namespace names independently of the rules for creating new names.
+ * Iceberg namespaces may have been created directly by engines and are passed as API values,
+ * rather than interpolated into SQL identifiers.
+ *
+ * @param scope the scope of the existing name
+ * @param name the existing name
+ * @return whether the existing name can be addressed
+ */
+ @Override
+ public CapabilityResult specificationOnExistingName(Scope scope, String name) {
+ if (scope != Scope.SCHEMA) {
+ return Capability.super.specificationOnExistingName(scope, name);
+ }
+ for (String segment : HierarchicalSchemaUtil.splitSchemaName(name, schemaSeparator)) {
+ if (segment.isEmpty()) {
+ return CapabilityResult.unsupported(
+ "An existing Iceberg namespace cannot have empty segments");
+ }
+ }
+ return CapabilityResult.SUPPORTED;
+ }
+
private CapabilityResult validateSegments(String name, String separator) {
String[] segments = HierarchicalSchemaUtil.splitSchemaName(name, separator);
for (String segment : segments) {
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
index 274321d8b5..145d785b6f 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
@@ -25,6 +25,26 @@ import org.junit.jupiter.api.Test;
public class TestIcebergCatalogCapability {
+ @Test
+ void testExistingLongNamespacesRemainAddressableWithoutRelaxingCreate() {
+ IcebergCatalogCapability capability = new IcebergCatalogCapability(":");
+ for (int length : new int[] {65, 100}) {
+ String name = "n".repeat(length);
+ Assertions.assertTrue(
+ capability.specificationOnExistingName(Capability.Scope.SCHEMA, name).supported());
+ Assertions.assertTrue(
+ capability
+ .specificationOnExistingName(Capability.Scope.SCHEMA, "parent:" + name)
+ .supported());
+ Assertions.assertFalse(
+ capability.specificationOnName(Capability.Scope.SCHEMA, name).supported());
+ Assertions.assertFalse(
+ capability.specificationOnExistingName(Capability.Scope.TABLE, name).supported());
+ }
+ Assertions.assertFalse(
+ capability.specificationOnExistingName(Capability.Scope.SCHEMA, "a::b").supported());
+ }
+
@Test
public void testSchemaNameSupportsConfiguredSeparator() {
IcebergCatalogCapability capability = new IcebergCatalogCapability(":");
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java
index 2dea855c92..1554ec6019 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java
@@ -22,6 +22,7 @@ import static org.apache.gravitino.catalog.CapabilityHelpers.applyCapabilities;
import static org.apache.gravitino.catalog.CapabilityHelpers.applyCaseSensitive;
import static org.apache.gravitino.catalog.CapabilityHelpers.withCapability;
+import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
@@ -32,6 +33,7 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
@@ -122,7 +124,7 @@ public class SchemaNormalizeDispatcher implements SchemaDispatcher {
@Override
public boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {
- return dispatcher.dropSchema(normalizeNameIdentifier(ident), cascade);
+ return dispatcher.dropSchema(normalizeExistingNameIdentifier(ident), cascade);
}
private boolean supportsHierarchicalSchema(Namespace namespace) {
@@ -150,4 +152,18 @@ public class SchemaNormalizeDispatcher implements SchemaDispatcher {
catalogManager,
capabilities -> applyCaseSensitive(schemaIdent, Capability.Scope.SCHEMA, capabilities));
}
+
+ private NameIdentifier normalizeExistingNameIdentifier(NameIdentifier schemaIdent) {
+ return withCapability(
+ schemaIdent,
+ catalogManager,
+ capabilities -> {
+ CapabilityResult result =
+ capabilities.specificationOnExistingName(Capability.Scope.SCHEMA, schemaIdent.name());
+ Preconditions.checkArgument(
+ result.supported(),
+ result.unsupportedMessage() + " Illegal name: " + schemaIdent.name());
+ return applyCaseSensitive(schemaIdent, Capability.Scope.SCHEMA, capabilities);
+ });
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaDropExistingNames.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaDropExistingNames.java
new file mode 100644
index 0000000000..bc8a1146a2
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaDropExistingNames.java
@@ -0,0 +1,81 @@
+/*
+ * 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.catalog;
+
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.connector.capability.CapabilityResult;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+class TestSchemaDropExistingNames {
+ @ParameterizedTest
+ @ValueSource(ints = {64, 65, 100})
+ void testExistingNamesUseExistingCapabilityAndKeepCaseFolding(int length) {
+ CatalogManager manager = Mockito.mock(CatalogManager.class);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ CatalogTestUtils.mockDoWithCatalog(manager, catalog);
+ Capability capability =
+ new Capability() {
+ /** {@inheritDoc} */
+ @Override
+ public CapabilityResult specificationOnExistingName(Scope scope, String name) {
+ return CapabilityResult.SUPPORTED;
+ }
+ /** {@inheritDoc} */
+ @Override
+ public CapabilityResult caseSensitiveOnName(Scope scope) {
+ return CapabilityResult.unsupported("case insensitive");
+ }
+ };
+ Mockito.when(catalog.capability()).thenReturn(capability);
+ SchemaDispatcher delegate = Mockito.mock(SchemaDispatcher.class);
+ SchemaNormalizeDispatcher dispatcher = new SchemaNormalizeDispatcher(delegate, manager);
+ String name = "N".repeat(length);
+ NameIdentifier requested = NameIdentifier.of("ml", "cat", name);
+ dispatcher.dropSchema(requested, true);
+ Mockito.verify(delegate).dropSchema(NameIdentifier.of("ml", "cat", name.toLowerCase()), true);
+ if (length > 64) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> dispatcher.createSchema(requested, null, null));
+ Mockito.verify(delegate, Mockito.never())
+ .createSchema(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {"bad?name", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789long"})
+ void testDefaultExistingNameRestrictionsArePreserved(String name) {
+ CatalogManager manager = Mockito.mock(CatalogManager.class);
+ BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);
+ CatalogTestUtils.mockDoWithCatalog(manager, catalog);
+ Mockito.when(catalog.capability()).thenReturn(new Capability() {});
+ SchemaDispatcher delegate = Mockito.mock(SchemaDispatcher.class);
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ new SchemaNormalizeDispatcher(delegate, manager)
+ .dropSchema(NameIdentifier.of("ml", "cat", name), false));
+ Mockito.verifyNoInteractions(delegate);
+ }
+}
diff --git a/docs/lakehouse-iceberg-catalog.md b/docs/lakehouse-iceberg-catalog.md
index 33daff931c..973cb7b6b4 100644
--- a/docs/lakehouse-iceberg-catalog.md
+++ b/docs/lakehouse-iceberg-catalog.md
@@ -152,6 +152,34 @@ on the URI scheme:
- To override the default, explicitly configure `io-impl`.
- Ensure that the corresponding storage bundle is available in the Iceberg catalog classpath.
+Catalogs with a remote warehouse reject client-supplied local filesystem locations, including
+`file:` URIs and paths without a scheme, with HTTP 400. This applies to table and view creation
+(including staged table creation), registration, location updates, namespace locations, and the
+`write.metadata.path` and `write.data.path` properties. An existing local namespace location is
+also rejected when a create request inherits it. ResolvingFileIO still permits locations on
+different remote storage systems, such as S3 and GCS, in the same catalog. Catalogs whose warehouse
+is a local path or `file:` URI retain local filesystem support for development and testing.
+
+With Iceberg REST authorization enabled, an explicit table location on create (including staged
+create), registration, or a `set-location` commit requires load access to every existing table
+whose location overlaps it. Equal, parent, and child directories overlap; names such as `table`
+and `table2` do not. Destination create and overwrite privileges are checked first, and denied
+source checks return 403 without disclosing the source table's name. A default-location create
+does not add a source scan. Filesystem dot segments and repeated separators are normalized for
+comparison; object-store keys retain their literal path segments.
+
+For JDBC backends, source discovery uses a single query of current metadata pointers and infers
+locations from the standard `<table-location>/metadata/<file>` layout. This lookup does not read
+other tables' metadata files and does not use a cross-request cache. Custom metadata layouts,
+including arbitrary `write.metadata.path` values, are outside this lookup's supported layout.
+Registration also preserves exact current metadata-pointer matching, including pointers outside
+the standard layout. This identity check does not provide complete overlap detection for custom
+layouts. Source discovery compares storage locations and metadata pointers rather than table
+UUIDs; register-overwrite still preserves the destination table UUID. Backends without bulk
+pointer lookup retain namespace discovery. Metadata read failures on that fallback path are
+propagated; only tables proven to have disappeared are skipped. Database lookup failures are
+also propagated, and destination authorization remains required.
+
Supports using static access-key-id and secret-access-key to access S3 data.
| Configuration item | Description | Default value | Required |
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/cache/SupportsMetadataLocation.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/cache/SupportsMetadataLocation.java
index ea52ae3888..42db3f8da9 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/cache/SupportsMetadataLocation.java
+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/cache/SupportsMetadataLocation.java
@@ -19,6 +19,9 @@
package org.apache.gravitino.iceberg.common.cache;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
import org.apache.iceberg.catalog.TableIdentifier;
/** An interface that supports retrieving the metadata location for a table. */
@@ -33,4 +36,26 @@ public interface SupportsMetadataLocation {
* @return the metadata location of the table as a String
*/
String metadataLocation(TableIdentifier tableIdentifier);
+
+ /**
+ * Looks up current metadata pointers whose standard-layout table roots may overlap a location.
+ *
+ * @param location requested table location
+ * @return candidate pointers, or empty when bulk lookup is not supported
+ */
+ default Optional<Map<TableIdentifier, String>> metadataLocationCandidates(String location) {
+ return Optional.empty();
+ }
+
+ /**
+ * Looks up overlapping standard-layout pointers and an exact registration source pointer.
+ *
+ * @param location requested table location
+ * @param metadataLocation requested metadata pointer, or null outside registration
+ * @return candidate pointers, or empty when bulk lookup is not supported
+ */
+ default Optional<Map<TableIdentifier, String>> metadataLocationCandidates(
+ String location, @Nullable String metadataLocation) {
+ return metadataLocationCandidates(location);
+ }
}
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 673e804ffa..39805cd33b 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
@@ -39,6 +39,7 @@ import org.apache.gravitino.iceberg.common.cache.TableMetadataCache;
import org.apache.gravitino.iceberg.common.utils.IcebergCatalogUtil;
import org.apache.gravitino.utils.ClassUtils;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.iceberg.BaseMetadataTable;
@@ -90,6 +91,7 @@ import org.apache.iceberg.rest.responses.UpdateNamespacePropertiesResponse;
import org.apache.iceberg.view.BaseView;
import org.apache.iceberg.view.View;
import org.apache.iceberg.view.ViewMetadata;
+import org.apache.iceberg.view.ViewMetadataParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -244,7 +246,23 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
public LoadTableResponse registerTable(Namespace namespace, RegisterTableRequest request) {
+ request.validate();
validateTableLocation(request.metadataLocation());
+ TableMetadata metadata =
+ request instanceof RegisterTableRequestWithMetadata
+ ? ((RegisterTableRequestWithMetadata) request).tableMetadata()
+ : loadTableMetadataFromLocation(request.metadataLocation());
+ validateTableLocation(metadata.location());
+ validateStorageProperties(metadata.properties());
+ Catalog loadedCatalog = getCatalog();
+ // Subclasses can enforce additional registration invariants through the original API.
+ if (loadedCatalog.getClass() == JdbcCatalogWithMetadataLocationSupport.class) {
+ TableIdentifier identifier = TableIdentifier.of(namespace, request.name());
+ getMetadataCache().invalidate(identifier);
+ ((JdbcCatalogWithMetadataLocationSupport) loadedCatalog)
+ .registerTableWithMetadata(identifier, metadata, request.overwrite());
+ return LoadTableResponse.builder().withTableMetadata(metadata).build();
+ }
try {
return CatalogHandlers.registerTable(getCatalog(), namespace, request);
} catch (NotFoundException e) {
@@ -271,6 +289,8 @@ public class IcebergCatalogWrapper implements AutoCloseable {
request.validate();
validateTableDefinition(request);
validateTableLocation(request.location());
+ validateStorageProperties(request.properties());
+ validateInheritedLocation(namespace, request.location());
Catalog loadedCatalog = getCatalog();
LoadTableResponse loadTableResponse;
try {
@@ -429,6 +449,34 @@ public class IcebergCatalogWrapper implements AutoCloseable {
return Optional.empty();
}
+ /**
+ * Returns potential overlapping standard-layout table pointers without reading table metadata.
+ *
+ * @param location requested table location
+ * @return candidate pointers, or empty when the backend has no bulk pointer lookup
+ */
+ public Optional<Map<TableIdentifier, String>> getTableMetadataLocationCandidates(
+ String location) {
+ return getTableMetadataLocationCandidates(location, null);
+ }
+
+ /**
+ * Returns overlapping standard-layout pointers and an exact registration source pointer.
+ *
+ * @param location requested table location
+ * @param metadataLocation requested metadata pointer, or null outside registration
+ * @return candidate pointers, or empty when bulk lookup is unsupported
+ */
+ public Optional<Map<TableIdentifier, String>> getTableMetadataLocationCandidates(
+ String location, @Nullable String metadataLocation) {
+ Catalog loadedCatalog = getCatalog();
+ if (loadedCatalog instanceof SupportsMetadataLocation) {
+ return ((SupportsMetadataLocation) loadedCatalog)
+ .metadataLocationCandidates(location, metadataLocation);
+ }
+ return Optional.empty();
+ }
+
public boolean tableExists(TableIdentifier tableIdentifier) {
return getCatalog().tableExists(tableIdentifier);
}
@@ -457,11 +505,7 @@ 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());
- }
- }
+ validateStorageUpdates(updateTableRequest);
getMetadataCache().invalidate(tableIdentifier);
validateDefaultSpecAndSortOrder(tableIdentifier, updateTableRequest);
LoadTableResponse loadTableResponse;
@@ -523,12 +567,21 @@ public class IcebergCatalogWrapper implements AutoCloseable {
public LoadViewResponse createView(Namespace namespace, CreateViewRequest request) {
request.validate();
+ validateTableLocation(request.location());
+ validateStorageProperties(request.properties());
+ validateInheritedLocation(namespace, request.location());
return CatalogHandlers.createView(getViewCatalog(), namespace, request);
}
public LoadViewResponse registerView(Namespace namespace, RegisterViewRequest request) {
request.validate();
+ validateTableLocation(request.metadataLocation());
try {
+ if (hasRemoteWarehouse() || S3FileIO.class.getName().equals(fileIOImpl())) {
+ ViewMetadata metadata = loadViewMetadataFromLocation(request.metadataLocation());
+ validateTableLocation(metadata.location());
+ validateStorageProperties(metadata.properties());
+ }
return CatalogHandlers.registerView(getViewCatalog(), namespace, request);
} catch (NotFoundException e) {
// As in registerTable: the metadata location comes from the request.
@@ -540,6 +593,7 @@ public class IcebergCatalogWrapper implements AutoCloseable {
public LoadViewResponse updateView(TableIdentifier viewIdentifier, UpdateTableRequest request) {
request.validate();
+ validateStorageUpdates(request);
return CatalogHandlers.updateView(getViewCatalog(), viewIdentifier, request);
}
@@ -639,6 +693,13 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
}
+ @VisibleForTesting
+ ViewMetadata loadViewMetadataFromLocation(String metadataLocation) {
+ try (FileIO fileIO = CatalogUtil.loadFileIO(fileIOImpl(), fileIOProperties(), null)) {
+ return ViewMetadataParser.read(fileIO.newInputFile(metadataLocation));
+ }
+ }
+
private TableMetadataCache loadTableMetadataCache(IcebergConfig config, Catalog catalog) {
String impl = config.get(IcebergConfig.TABLE_METADATA_CACHE_IMPL);
if (StringUtils.isBlank(impl)) {
@@ -705,7 +766,16 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
private void validateTableLocation(@Nullable String location) {
- if (location == null || !S3FileIO.class.getName().equals(fileIOImpl())) {
+ if (location == null) {
+ return;
+ }
+ if (hasRemoteWarehouse() && isLocalLocation(location)) {
+ throw new BadRequestException(
+ "Invalid storage location '%s': a catalog with a remote warehouse cannot access the"
+ + " server's local filesystem",
+ location);
+ }
+ if (!S3FileIO.class.getName().equals(fileIOImpl())) {
return;
}
String[] parts = location.split("://", 2);
@@ -717,6 +787,50 @@ public class IcebergCatalogWrapper implements AutoCloseable {
}
}
+ private void validateStorageProperties(@Nullable Map<String, String> properties) {
+ if (properties != null) {
+ validateTableLocation(properties.get(TableProperties.WRITE_METADATA_LOCATION));
+ validateTableLocation(properties.get(TableProperties.WRITE_DATA_LOCATION));
+ }
+ }
+
+ private void validateStorageUpdates(UpdateTableRequest request) {
+ for (MetadataUpdate update : request.updates()) {
+ if (update instanceof MetadataUpdate.SetLocation) {
+ validateTableLocation(((MetadataUpdate.SetLocation) update).location());
+ } else if (update instanceof MetadataUpdate.SetProperties) {
+ validateStorageProperties(((MetadataUpdate.SetProperties) update).updated());
+ }
+ }
+ }
+
+ private void validateInheritedLocation(Namespace namespace, @Nullable String location) {
+ if (location == null && hasRemoteWarehouse()) {
+ // Existing namespaces may already have a local location. Check it before an implicit
+ // create uses it, as well as rejecting new local namespace locations.
+ SupportsNamespaces namespaceCatalog = getNamespaceCatalog();
+ if (namespaceCatalog != null) {
+ validateTableLocation(
+ namespaceCatalog.loadNamespaceMetadata(namespace).get(IcebergConstants.LOCATION));
+ }
+ }
+ }
+
+ private boolean hasRemoteWarehouse() {
+ String warehouse = icebergConfig.get(IcebergConfig.CATALOG_WAREHOUSE);
+ return StringUtils.isNotBlank(warehouse) && !isLocalLocation(warehouse);
+ }
+
+ private static boolean isLocalLocation(String location) {
+ if (StringUtils.isBlank(location)) {
+ return true;
+ }
+ // Use Hadoop's path parsing, matching ResolvingFileIO's local fallback. This also handles
+ // file:/ paths and paths without a scheme, rather than checking only the file:// prefix.
+ String scheme = new Path(location).toUri().getScheme();
+ return scheme == null || "file".equalsIgnoreCase(scheme);
+ }
+
/**
* 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.
@@ -780,6 +894,7 @@ public class IcebergCatalogWrapper implements AutoCloseable {
if (properties == null) {
return;
}
+ validateTableLocation(properties.get(IcebergConstants.LOCATION));
if (getCatalog() instanceof JdbcCatalog) {
properties.forEach(
(key, value) ->
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/RegisterTableRequestWithMetadata.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/RegisterTableRequestWithMetadata.java
new file mode 100644
index 0000000000..d9fda19b72
--- /dev/null
+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/RegisterTableRequestWithMetadata.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.common.ops;
+
+import java.util.Objects;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.rest.requests.RegisterTableRequest;
+
+/**
+ * Carries the metadata snapshot read for a single registration through authorization and commit.
+ */
+public final class RegisterTableRequestWithMetadata implements RegisterTableRequest {
+ private final RegisterTableRequest request;
+ private final TableMetadata metadata;
+
+ /**
+ * Wraps a registration with the metadata already read from its requested file.
+ *
+ * @param request original registration
+ * @param metadata metadata snapshot read for this request
+ */
+ public RegisterTableRequestWithMetadata(RegisterTableRequest request, TableMetadata metadata) {
+ this.request = Objects.requireNonNull(request, "request");
+ this.metadata = Objects.requireNonNull(metadata, "metadata");
+ }
+
+ /**
+ * Returns this request's metadata snapshot; this is not a cross-request cache.
+ *
+ * @return metadata snapshot
+ */
+ public TableMetadata tableMetadata() {
+ return metadata;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String name() {
+ return request.name();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String metadataLocation() {
+ return request.metadataLocation();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean overwrite() {
+ return request.overwrite();
+ }
+}
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergTableLocationUtils.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergTableLocationUtils.java
new file mode 100644
index 0000000000..4eea789804
--- /dev/null
+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergTableLocationUtils.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.common.utils;
+
+import java.net.URI;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.hadoop.fs.Path;
+
+/** Location comparisons and JDBC lookup patterns for Iceberg's standard metadata layout. */
+public final class IcebergTableLocationUtils {
+ private static final String METADATA_DIRECTORY = "/metadata/";
+
+ private IcebergTableLocationUtils() {}
+
+ /**
+ * Normalizes filesystem dot segments and separators, local URI forms and equivalent S3 schemes.
+ * Dot segments and repeated separators in object-store keys are preserved.
+ *
+ * @param location storage location, possibly absent
+ * @return normalized location, or an empty string for an absent location
+ */
+ public static String normalize(@Nullable String location) {
+ if (location == null) {
+ return "";
+ }
+ String value = location.trim();
+ if (value.startsWith("s3a://") || value.startsWith("s3n://")) {
+ value = "s3://" + value.substring(6);
+ } else if (value.regionMatches(true, 0, "file:", 0, 5)) {
+ String path = value.substring(5);
+ while (path.startsWith("//")) {
+ path = path.substring(1);
+ }
+ value = "file:" + Paths.get(path.startsWith("/") ? path : "/" + path).normalize();
+ } else if (!value.isEmpty() && new Path(value).toUri().getScheme() == null) {
+ value = "file:" + Paths.get(value).toAbsolutePath().normalize();
+ } else if (value.regionMatches(true, 0, "hdfs:", 0, 5)
+ || value.regionMatches(true, 0, "viewfs:", 0, 7)) {
+ URI uri = new Path(value).toUri();
+ value =
+ uri.getScheme().toLowerCase(Locale.ROOT)
+ + ":"
+ + (uri.getAuthority() == null ? "" : "//" + uri.getAuthority())
+ + Paths.get(uri.getPath()).normalize();
+ }
+ while (value.endsWith("/") && !value.endsWith(":/")) {
+ value = value.substring(0, value.length() - 1);
+ }
+ return value;
+ }
+
+ /**
+ * Tests equality or containment at a whole path-segment boundary.
+ *
+ * @param left first storage location
+ * @param right second storage location
+ * @return whether either location contains the other
+ */
+ public static boolean overlaps(String left, String right) {
+ String a = normalize(left);
+ String b = normalize(right);
+ return !a.isEmpty()
+ && !b.isEmpty()
+ && (a.equals(b) || a.startsWith(directory(b)) || b.startsWith(directory(a)));
+ }
+
+ /**
+ * Infers the table root for a standard {@code <table>/metadata/<file>} pointer.
+ *
+ * @param metadataLocation current metadata pointer
+ * @return the inferred root, or empty for a nonstandard layout
+ */
+ public static Optional<String> tableLocation(String metadataLocation) {
+ String value = normalize(metadataLocation);
+ int index = value.lastIndexOf(METADATA_DIRECTORY);
+ if (index < 0 || value.substring(index + METADATA_DIRECTORY.length()).contains("/")) {
+ return Optional.empty();
+ }
+ return Optional.of(value.substring(0, index));
+ }
+
+ /**
+ * Builds bound LIKE patterns for overlapping standard metadata pointers. The SQL must use {@code
+ * ESCAPE '!'}; user-supplied percent signs, underscores and escape characters are literal.
+ *
+ * @param location requested table location
+ * @return patterns covering descendants and the metadata directories of ancestors
+ */
+ public static List<String> metadataLocationPatterns(String location) {
+ String normalized = normalize(location);
+ Set<String> forms = new LinkedHashSet<>();
+ forms.add(normalized);
+ if (normalized.startsWith("s3://")) {
+ forms.add("s3a://" + normalized.substring(5));
+ forms.add("s3n://" + normalized.substring(5));
+ } else if (normalized.startsWith("file:/")) {
+ forms.add("file://" + normalized.substring(5));
+ forms.add(normalized.substring(5));
+ }
+ Set<String> patterns = new LinkedHashSet<>();
+ for (String form : forms) {
+ patterns.add(escape(directory(form)) + "%");
+ String parent = form;
+ while (!parent.isEmpty()) {
+ patterns.add(escape(directory(parent) + "metadata/") + "%");
+ int slash = parent.lastIndexOf('/');
+ int scheme = parent.indexOf("://");
+ if (slash <= (scheme >= 0 ? scheme + 2 : 0)) {
+ break;
+ }
+ parent = parent.substring(0, slash);
+ }
+ }
+ return new ArrayList<>(patterns);
+ }
+
+ private static String directory(String value) {
+ return value.endsWith("/") ? value : value + "/";
+ }
+
+ private static String escape(String value) {
+ return value.replace("!", "!!").replace("%", "!%").replace("_", "!_");
+ }
+}
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java
index 82782f8888..0234fdf900 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java
+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java
@@ -19,7 +19,9 @@
package org.apache.iceberg;
import com.google.common.base.Preconditions;
+import java.util.Objects;
import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
/**
* Shared helpers for {@link org.apache.iceberg.catalog.Catalog#registerTable(TableIdentifier,
@@ -96,5 +98,44 @@ public class MetastoreRegisterTableUtils {
catalog.metricsReporter());
}
+ /**
+ * Registers a metadata snapshot already read and authorized by the caller, without reopening its
+ * file. Existing destination metadata is still read for an atomic overwrite.
+ *
+ * @param catalog destination catalog
+ * @param identifier destination table
+ * @param metadata snapshot read from the requested metadata file
+ * @param overwrite whether the destination can be replaced
+ * @param metadataLocationOverwrite atomic pointer replacement
+ */
+ public static void registerTableWithMetadata(
+ BaseMetastoreCatalog catalog,
+ TableIdentifier identifier,
+ TableMetadata metadata,
+ boolean overwrite,
+ MetadataLocationOverwrite metadataLocationOverwrite) {
+ Preconditions.checkArgument(
+ identifier != null && catalog.isValidIdentifier(identifier),
+ "Invalid identifier: %s",
+ identifier);
+ Preconditions.checkArgument(
+ metadata.metadataFileLocation() != null,
+ "Registered metadata must retain its file location");
+ TableOperations ops = catalog.newTableOps(identifier);
+ TableMetadata base = ops.current();
+ if (base == null) {
+ ops.commit(null, metadata);
+ } else {
+ if (!overwrite) {
+ throw new AlreadyExistsException("Table already exists: %s", identifier);
+ }
+ Preconditions.checkArgument(
+ Objects.equals(base.uuid(), metadata.uuid()),
+ "Cannot overwrite a table with a different table UUID");
+ metadataLocationOverwrite.overwrite(
+ identifier, base.metadataFileLocation(), metadata.metadataFileLocation());
+ }
+ }
+
private MetastoreRegisterTableUtils() {}
}
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java
index d1b17c2ced..f6b3f6724c 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java
+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java
@@ -20,13 +20,24 @@
package org.apache.iceberg.jdbc;
import com.google.common.base.Preconditions;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nullable;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.iceberg.common.ClosableJdbcCatalog;
import org.apache.gravitino.iceberg.common.cache.SupportsMetadataLocation;
+import org.apache.gravitino.iceberg.common.utils.IcebergTableLocationUtils;
import org.apache.iceberg.MetastoreRegisterTableUtils;
import org.apache.iceberg.Table;
+import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.CommitFailedException;
import org.apache.iceberg.jdbc.JdbcUtil.SchemaVersion;
@@ -67,6 +78,84 @@ public class JdbcCatalogWithMetadataLocationSupport extends ClosableJdbcCatalog
return table.get(METADATA_LOCATION_PROP);
}
+ /** {@inheritDoc} */
+ @Override
+ public Optional<Map<TableIdentifier, String>> metadataLocationCandidates(String location) {
+ return metadataLocationCandidates(location, null);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Optional<Map<TableIdentifier, String>> metadataLocationCandidates(
+ String location, @Nullable String metadataLocation) {
+ List<String> patterns = IcebergTableLocationUtils.metadataLocationPatterns(location);
+ Set<String> exactPointers = new LinkedHashSet<>();
+ if (metadataLocation != null) {
+ exactPointers.add(metadataLocation);
+ String normalized = IcebergTableLocationUtils.normalize(metadataLocation);
+ exactPointers.add(normalized);
+ if (normalized.startsWith("s3://")) {
+ exactPointers.add("s3a://" + normalized.substring(5));
+ exactPointers.add("s3n://" + normalized.substring(5));
+ }
+ }
+ String predicate =
+ String.join(
+ " OR ",
+ Collections.nCopies(patterns.size(), METADATA_LOCATION_PROP + " LIKE ? ESCAPE '!'"));
+ String query =
+ "SELECT table_namespace, table_name, metadata_location FROM iceberg_tables"
+ + " WHERE catalog_name = ?"
+ + (jdbcSchemaVersion == SchemaVersion.V0
+ ? ""
+ : " AND (iceberg_type = 'TABLE' OR iceberg_type IS NULL)")
+ + " AND ("
+ + predicate
+ // Filesystem pointers can contain equivalent dot segments and repeated separators.
+ // Return those strings for lexical comparison without opening their metadata files.
+ + " OR LOWER(metadata_location) LIKE 'file:%'"
+ + " OR LOWER(metadata_location) LIKE 'hdfs:%'"
+ + " OR LOWER(metadata_location) LIKE 'viewfs:%'"
+ + " OR metadata_location NOT LIKE '%://%'"
+ + (exactPointers.isEmpty()
+ ? ""
+ : " OR metadata_location IN ("
+ + String.join(",", Collections.nCopies(exactPointers.size(), "?"))
+ + ")")
+ + ")";
+ try {
+ return Optional.of(
+ jdbcConnections.run(
+ connection -> {
+ Map<TableIdentifier, String> rows = new LinkedHashMap<>();
+ try (PreparedStatement statement = connection.prepareStatement(query)) {
+ statement.setString(1, jdbcCatalogName);
+ for (int i = 0; i < patterns.size(); i++) {
+ statement.setString(i + 2, patterns.get(i));
+ }
+ int parameter = patterns.size() + 2;
+ for (String pointer : exactPointers) {
+ statement.setString(parameter++, pointer);
+ }
+ try (ResultSet result = statement.executeQuery()) {
+ while (result.next()) {
+ rows.put(
+ TableIdentifier.of(
+ JdbcUtil.stringToNamespace(result.getString(1)), result.getString(2)),
+ result.getString(3));
+ }
+ }
+ }
+ return rows;
+ }));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new UncheckedInterruptedException(e, "Interrupted during metadata pointer lookup");
+ } catch (SQLException e) {
+ throw new UncheckedSQLException(e, "Failed to look up metadata pointers");
+ }
+ }
+
/**
* Check if the JDBC catalog schema version supports view operations. View operations are
* supported from V1 schema version onwards.
@@ -94,6 +183,19 @@ public class JdbcCatalogWithMetadataLocationSupport extends ClosableJdbcCatalog
this, identifier, metadataFileLocation, overwrite, this::overwriteMetadataLocation);
}
+ /**
+ * Registers an already read metadata snapshot without opening the input file again.
+ *
+ * @param identifier destination table
+ * @param metadata metadata snapshot read and authorized for this request
+ * @param overwrite whether an existing registration can be replaced
+ */
+ public void registerTableWithMetadata(
+ TableIdentifier identifier, TableMetadata metadata, boolean overwrite) {
+ MetastoreRegisterTableUtils.registerTableWithMetadata(
+ this, identifier, metadata, overwrite, this::overwriteMetadataLocation);
+ }
+
private void overwriteMetadataLocation(
TableIdentifier tableIdentifier, String oldMetadataLocation, String newMetadataLocation) {
try {
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 2d37a9e601..b25544ad12 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
@@ -138,12 +138,17 @@ public class TestIcebergCatalogWrapper {
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()))
+ String pointer = location + "/metadata/v1.metadata.json";
+ TableMetadata metadata = Mockito.mock(TableMetadata.class);
+ Mockito.when(metadata.location()).thenReturn(location);
+ Mockito.when(metadata.properties()).thenReturn(Collections.emptyMap());
+ Mockito.doReturn(metadata).when(wrapper).loadTableMetadataFromLocation(pointer);
+ Mockito.when(catalog.registerTable(Mockito.any(), Mockito.eq(pointer), 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();
+ ImmutableRegisterTableRequest.builder().name("t").metadataLocation(pointer).build();
UpdateTableRequest update =
new UpdateTableRequest(
Collections.emptyList(),
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergStorageLocations.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergStorageLocations.java
new file mode 100644
index 0000000000..dc92bf4af6
--- /dev/null
+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergStorageLocations.java
@@ -0,0 +1,433 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.common.ops;
+
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.iceberg.MetadataUpdate;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.SupportsNamespaces;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.BadRequestException;
+import org.apache.iceberg.io.ResolvingFileIO;
+import org.apache.iceberg.jdbc.JdbcCatalogWithMetadataLocationSupport;
+import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
+import org.apache.iceberg.rest.requests.CreateViewRequest;
+import org.apache.iceberg.rest.requests.ImmutableCreateViewRequest;
+import org.apache.iceberg.rest.requests.ImmutableRegisterTableRequest;
+import org.apache.iceberg.rest.requests.ImmutableRegisterViewRequest;
+import org.apache.iceberg.rest.requests.UpdateNamespacePropertiesRequest;
+import org.apache.iceberg.rest.requests.UpdateTableRequest;
+import org.apache.iceberg.rest.responses.LoadTableResponse;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.view.ImmutableSQLViewRepresentation;
+import org.apache.iceberg.view.ImmutableViewVersion;
+import org.apache.iceberg.view.ViewMetadata;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.function.Executable;
+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.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+class TestIcebergStorageLocations {
+ private static final Namespace NAMESPACE = Namespace.of("locations");
+ private static final TableIdentifier TABLE = TableIdentifier.of(NAMESPACE, "table");
+ private static final Schema SCHEMA =
+ new Schema(Types.NestedField.optional(1, "id", Types.LongType.get()));
+
+ @ParameterizedTest
+ @MethodSource("localCreates")
+ void testRemoteWarehouseRejectsLocalCreateBeforeWriting(
+ boolean explicitIO, boolean staged, String location, @TempDir Path tempDir) throws Exception {
+ Map<String, String> properties = config(tempDir, "s3://bucket/warehouse", explicitIO);
+ Path localTable = tempDir.resolve("local_table");
+ String rejected = location.replace("LOCAL", localTable.toString());
+ CreateTableRequest request = createRequest(rejected, staged, Map.of());
+ try (IcebergCatalogWrapper wrapper = new IcebergCatalogWrapper(new IcebergConfig(properties))) {
+ assertRejected(rejected, () -> wrapper.createTable(NAMESPACE, request));
+ Assertions.assertFalse(Files.exists(localTable));
+ Assertions.assertFalse(Files.exists(tempDir.resolve("catalog.db")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/table", "file:/tmp/table", "/tmp/table", "relative/table"})
+ void testRemoteWarehouseRejectsRegisterReadAndLocationUpdates(String location, @TempDir Path dir)
+ throws Exception {
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ assertRejected(
+ location,
+ () ->
+ wrapper.registerTable(
+ NAMESPACE,
+ ImmutableRegisterTableRequest.builder()
+ .name("table")
+ .metadataLocation(location)
+ .build()));
+ assertRejected(location, () -> wrapper.loadTableMetadataFromLocation(location));
+ assertRejected(
+ location,
+ () ->
+ wrapper.updateTable(
+ TABLE,
+ new UpdateTableRequest(
+ List.of(), List.of(new MetadataUpdate.SetLocation(location)))));
+ Assertions.assertFalse(Files.exists(dir.resolve("catalog.db")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"write.metadata.path", "write.data.path"})
+ void testRemoteWarehouseRejectsLocalWriteProperties(String property, @TempDir Path dir)
+ throws Exception {
+ String location = dir.resolve("local_metadata").toUri().toString();
+ Map<String, String> localProperties = Map.of(property, location);
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ for (boolean staged : List.of(false, true)) {
+ assertRejected(
+ location,
+ () ->
+ wrapper.createTable(
+ NAMESPACE, createRequest("s3://bucket/table", staged, localProperties)));
+ }
+ UpdateTableRequest update =
+ new UpdateTableRequest(
+ List.of(), List.of(new MetadataUpdate.SetProperties(localProperties)));
+ assertRejected(location, () -> wrapper.updateTable(TABLE, update));
+ assertRejected(location, () -> wrapper.updateView(TABLE, update));
+ assertRejected(
+ location,
+ () -> wrapper.createView(NAMESPACE, viewRequest("s3://bucket/view", localProperties)));
+ Assertions.assertFalse(Files.exists(dir.resolve("catalog.db")));
+ Assertions.assertFalse(Files.exists(dir.resolve("local_metadata")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/namespace", "/tmp/namespace"})
+ void testRemoteWarehouseRejectsLocalNamespaceLocations(String location, @TempDir Path dir)
+ throws Exception {
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ assertRejected(
+ location,
+ () ->
+ wrapper.createNamespace(
+ CreateNamespaceRequest.builder()
+ .withNamespace(NAMESPACE)
+ .setProperties(new HashMap<>(Map.of(IcebergConstants.LOCATION, location)))
+ .build()));
+ assertRejected(
+ location,
+ () ->
+ wrapper.updateNamespaceProperties(
+ NAMESPACE,
+ UpdateNamespacePropertiesRequest.builder()
+ .update(IcebergConstants.LOCATION, location)
+ .build()));
+ Assertions.assertFalse(wrapper.namespaceExists(NAMESPACE));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("registeredLocalLocations")
+ void testEveryBackendRejectsEmbeddedLocalTableLocations(
+ String property, boolean preloaded, boolean customJdbc, @TempDir Path dir) throws Exception {
+ String pointer = "s3://bucket/shared/v1.metadata.json";
+ String local = dir.resolve("local").toUri().toString();
+ TableMetadata metadata =
+ TableMetadata.newTableMetadata(
+ SCHEMA,
+ PartitionSpec.unpartitioned(),
+ property.equals("location") ? local : "s3://bucket/table",
+ property.equals("location") ? Map.of() : Map.of(property, local));
+ try (IcebergCatalogWrapper wrapper =
+ Mockito.spy(
+ new IcebergCatalogWrapper(
+ new IcebergConfig(config(dir, "s3://bucket/warehouse", false))))) {
+ Catalog backend =
+ customJdbc ? Mockito.mock(CustomJdbcCatalog.class) : Mockito.mock(Catalog.class);
+ Mockito.doReturn(backend).when(wrapper).getCatalog();
+ Mockito.doReturn(metadata).when(wrapper).loadTableMetadataFromLocation(pointer);
+ var original =
+ ImmutableRegisterTableRequest.builder().name("table").metadataLocation(pointer).build();
+ var request = preloaded ? new RegisterTableRequestWithMetadata(original, metadata) : original;
+ assertRejected(local, () -> wrapper.registerTable(NAMESPACE, request));
+ Mockito.verify(backend, Mockito.never())
+ .registerTable(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean());
+ Assertions.assertFalse(Files.exists(dir.resolve("local")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"location", "write.metadata.path", "write.data.path"})
+ void testRegisterViewRejectsEmbeddedLocalLocations(String property, @TempDir Path dir)
+ throws Exception {
+ String pointer = "s3://bucket/shared/v1.metadata.json";
+ String local = dir.resolve("local_view").toUri().toString();
+ ViewMetadata metadata = Mockito.mock(ViewMetadata.class);
+ Mockito.when(metadata.location())
+ .thenReturn(property.equals("location") ? local : "s3://bucket/view");
+ Mockito.when(metadata.properties())
+ .thenReturn(property.equals("location") ? Map.of() : Map.of(property, local));
+ try (IcebergCatalogWrapper wrapper =
+ Mockito.spy(
+ new IcebergCatalogWrapper(
+ new IcebergConfig(config(dir, "s3://bucket/warehouse", false))))) {
+ Mockito.doReturn(metadata).when(wrapper).loadViewMetadataFromLocation(pointer);
+ assertRejected(
+ local,
+ () ->
+ wrapper.registerView(
+ NAMESPACE,
+ ImmutableRegisterViewRequest.builder()
+ .name("view")
+ .metadataLocation(pointer)
+ .build()));
+ Mockito.verify(wrapper, Mockito.never()).getCatalog();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testRemoteWarehouseRejectsInheritedLocalNamespace(boolean staged, @TempDir Path dir)
+ throws Exception {
+ String location = dir.resolve("local_namespace").toUri().toString();
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ // Simulate namespace metadata created before location validation was introduced.
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(NAMESPACE).build());
+ ((SupportsNamespaces) wrapper.getCatalog())
+ .setProperties(NAMESPACE, Map.of(IcebergConstants.LOCATION, location));
+ assertRejected(
+ location, () -> wrapper.createTable(NAMESPACE, createRequest(null, staged, Map.of())));
+ assertRejected(location, () -> wrapper.createView(NAMESPACE, viewRequest(null, Map.of())));
+ Assertions.assertFalse(wrapper.tableExists(TABLE));
+ Assertions.assertFalse(Files.exists(dir.resolve("local_namespace")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/view", "/tmp/view"})
+ void testRemoteWarehouseRejectsLocalViewLocations(String location, @TempDir Path dir)
+ throws Exception {
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ assertRejected(
+ location, () -> wrapper.createView(NAMESPACE, viewRequest(location, Map.of())));
+ assertRejected(
+ location,
+ () ->
+ wrapper.registerView(
+ NAMESPACE,
+ ImmutableRegisterViewRequest.builder()
+ .name("view")
+ .metadataLocation(location)
+ .build()));
+ assertRejected(
+ location,
+ () ->
+ wrapper.updateView(
+ TABLE,
+ new UpdateTableRequest(
+ List.of(), List.of(new MetadataUpdate.SetLocation(location)))));
+ Assertions.assertFalse(Files.exists(dir.resolve("catalog.db")));
+ }
+ }
+
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(
+ strings = {
+ "s3://bucket/table",
+ "s3a://bucket/table",
+ "gs://bucket/table",
+ "abfss://[email protected]/table",
+ "hdfs://namenode/table"
+ })
+ void testResolvingFileIOPreservesCrossStorageLocations(
+ @Nullable String location, @TempDir Path dir) throws Exception {
+ IcebergCatalogWrapper wrapper =
+ Mockito.spy(
+ new IcebergCatalogWrapper(
+ new IcebergConfig(config(dir, "s3://bucket/warehouse", false))));
+ Catalog catalog = Mockito.mock(Catalog.class);
+ Mockito.doReturn(catalog).when(wrapper).getCatalog();
+ IllegalStateException backend = new IllegalStateException("backend reached");
+ Mockito.when(catalog.buildTable(Mockito.any(), Mockito.any())).thenThrow(backend);
+ try (wrapper) {
+ Assertions.assertSame(
+ backend,
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> wrapper.createTable(NAMESPACE, createRequest(location, false, Map.of()))));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"s3://bucket/table", "gs://bucket/table"})
+ void testRemoteStagedCreateWithoutCloudClients(String location, @TempDir Path dir)
+ throws Exception {
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, "s3://bucket/warehouse", false)))) {
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(NAMESPACE).build());
+ LoadTableResponse response =
+ wrapper.createTable(NAMESPACE, createRequest(location, true, Map.of()));
+ Assertions.assertEquals(location, response.tableMetadata().location());
+ Assertions.assertFalse(wrapper.tableExists(TABLE));
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+ void testLocalWarehouseStillCreatesAndLoadsLocalTables(
+ boolean explicitIO, boolean bareWarehouse, @TempDir Path dir) throws Exception {
+ String warehouse =
+ bareWarehouse
+ ? dir.resolve("warehouse").toString()
+ : dir.resolve("warehouse").toUri().toString();
+ try (IcebergCatalogWrapper wrapper =
+ new IcebergCatalogWrapper(new IcebergConfig(config(dir, warehouse, explicitIO)))) {
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(NAMESPACE).build());
+ LoadTableResponse response =
+ wrapper.createTable(
+ NAMESPACE,
+ createRequest(dir.resolve("local_table").toUri().toString(), false, Map.of()));
+ Assertions.assertTrue(wrapper.tableExists(TABLE));
+ Assertions.assertTrue(
+ Files.isRegularFile(Paths.get(URI.create(response.metadataLocation()))));
+ Assertions.assertEquals(
+ response.metadataLocation(), wrapper.loadTable(TABLE).metadataLocation());
+ }
+ }
+
+ private static Stream<Arguments> localCreates() {
+ return Stream.of(false, true)
+ .flatMap(
+ explicitIO ->
+ Stream.of(false, true)
+ .flatMap(
+ staged ->
+ Stream.of(
+ "file://LOCAL",
+ "file:LOCAL",
+ "FILE://LOCAL",
+ "LOCAL",
+ "relative/path",
+ "//localhost/tmp/table",
+ "")
+ .map(location -> Arguments.of(explicitIO, staged, location))));
+ }
+
+ private static Map<String, String> config(Path dir, String warehouse, boolean explicitIO) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put(IcebergConstants.CATALOG_BACKEND, "jdbc");
+ properties.put(IcebergConstants.URI, "jdbc:sqlite:" + dir.resolve("catalog.db"));
+ properties.put(IcebergConstants.GRAVITINO_JDBC_DRIVER, "org.sqlite.JDBC");
+ properties.put(IcebergConstants.WAREHOUSE, warehouse);
+ if (explicitIO) {
+ properties.put(IcebergConstants.IO_IMPL, ResolvingFileIO.class.getName());
+ }
+ return properties;
+ }
+
+ private static Stream<Arguments> registeredLocalLocations() {
+ return Stream.of("location", "write.metadata.path", "write.data.path")
+ .flatMap(
+ property ->
+ Stream.of(false, true)
+ .flatMap(
+ preloaded ->
+ Stream.of(false, true)
+ .map(customJdbc -> Arguments.of(property, preloaded, customJdbc))));
+ }
+
+ private static CreateTableRequest createRequest(
+ @Nullable String location, boolean staged, Map<String, String> properties) {
+ CreateTableRequest.Builder builder =
+ CreateTableRequest.builder()
+ .withName(TABLE.name())
+ .withSchema(SCHEMA)
+ .setProperties(new HashMap<>(properties));
+ if (location != null) {
+ builder.withLocation(location);
+ }
+ if (staged) {
+ builder.stageCreate();
+ }
+ return builder.build();
+ }
+
+ private static void assertRejected(String location, Executable action) {
+ BadRequestException failure = Assertions.assertThrows(BadRequestException.class, action);
+ Assertions.assertTrue(failure.getMessage().contains(location));
+ }
+
+ private static class CustomJdbcCatalog extends JdbcCatalogWithMetadataLocationSupport {
+ private CustomJdbcCatalog() {
+ super(false);
+ }
+ }
+
+ private static CreateViewRequest viewRequest(
+ @Nullable String location, Map<String, String> properties) {
+ ImmutableCreateViewRequest.Builder builder =
+ ImmutableCreateViewRequest.builder()
+ .name("view")
+ .schema(SCHEMA)
+ .properties(properties)
+ .viewVersion(
+ ImmutableViewVersion.builder()
+ .versionId(1)
+ .schemaId(SCHEMA.schemaId())
+ .timestampMillis(System.currentTimeMillis())
+ .defaultNamespace(NAMESPACE)
+ .addRepresentations(
+ ImmutableSQLViewRepresentation.builder()
+ .dialect("spark")
+ .sql("SELECT 1 AS id")
+ .build())
+ .build());
+ if (location != null) {
+ builder.location(location);
+ }
+ return builder.build();
+ }
+}
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestJdbcRegistrationMetadataReuse.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestJdbcRegistrationMetadataReuse.java
new file mode 100644
index 0000000000..d163231dba
--- /dev/null
+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestJdbcRegistrationMetadataReuse.java
@@ -0,0 +1,198 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.common.ops;
+
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.hadoop.HadoopFileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.jdbc.JdbcCatalogWithMetadataLocationSupport;
+import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
+import org.apache.iceberg.rest.requests.ImmutableRegisterTableRequest;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mockito;
+
+/** Verifies JDBC registration consumes the metadata snapshot authorized for that request. */
+public class TestJdbcRegistrationMetadataReuse {
+ private static final AtomicInteger READS = new AtomicInteger();
+ private static final Map<String, AtomicInteger> PATH_READS = new ConcurrentHashMap<>();
+
+ @Test
+ void testRegistersSameSnapshotWithoutReopeningFile(@TempDir Path dir) throws Exception {
+ IcebergConfig config =
+ new IcebergConfig(
+ Map.of(
+ "catalog-backend",
+ "jdbc",
+ "uri",
+ "jdbc:sqlite:" + dir.resolve("catalog.db"),
+ "jdbc-driver",
+ "org.sqlite.JDBC",
+ "warehouse",
+ dir.resolve("warehouse").toUri().toString(),
+ "io-impl",
+ CountingFileIO.class.getName()));
+ try (IcebergCatalogWrapper wrapper = new IcebergCatalogWrapper(config)) {
+ Namespace ns = Namespace.of("ns");
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(ns).build());
+ String pointer =
+ wrapper
+ .createTable(
+ ns,
+ CreateTableRequest.builder()
+ .withName("source")
+ .withSchema(
+ new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())))
+ .build())
+ .metadataLocation();
+ READS.set(0);
+ TableMetadata metadata = wrapper.loadTableMetadataFromLocation(pointer);
+ var original =
+ ImmutableRegisterTableRequest.builder().name("copy").metadataLocation(pointer).build();
+ var request = new RegisterTableRequestWithMetadata(original, metadata);
+ Assertions.assertFalse(request.overwrite());
+ request.validate();
+ var registered = wrapper.registerTable(ns, request);
+ Assertions.assertEquals(
+ 1, READS.get(), "Registration must not reopen an already read metadata file");
+ Assertions.assertEquals(metadata.uuid(), registered.tableMetadata().uuid());
+ Assertions.assertEquals(metadata.location(), registered.tableMetadata().location());
+ Assertions.assertEquals(metadata.properties(), registered.tableMetadata().properties());
+ Assertions.assertEquals(
+ pointer, wrapper.getTableMetadataLocation(TableIdentifier.of(ns, "copy")).orElseThrow());
+ Assertions.assertEquals(
+ metadata.uuid(),
+ wrapper.loadTable(TableIdentifier.of(ns, "copy")).tableMetadata().uuid());
+ Assertions.assertThrows(
+ AlreadyExistsException.class, () -> wrapper.registerTable(ns, request));
+ var overwrite =
+ new RegisterTableRequestWithMetadata(
+ ImmutableRegisterTableRequest.builder()
+ .name("copy")
+ .metadataLocation(pointer)
+ .overwrite(true)
+ .build(),
+ metadata);
+ Assertions.assertTrue(overwrite.overwrite());
+ Assertions.assertEquals(pointer, wrapper.registerTable(ns, overwrite).metadataLocation());
+
+ TableIdentifier copy = TableIdentifier.of(ns, "copy");
+ wrapper.getCatalog().loadTable(copy).updateProperties().set("marker", "new").commit();
+ Assertions.assertNotEquals(pointer, wrapper.getTableMetadataLocation(copy).orElseThrow());
+ int beforeOverwrite = PATH_READS.get(pointer).get();
+ var restored = wrapper.registerTable(ns, overwrite);
+ Assertions.assertEquals(
+ beforeOverwrite,
+ PATH_READS.get(pointer).get(),
+ "Overwriting must not reopen the authorized metadata snapshot");
+ Assertions.assertEquals(pointer, restored.metadataLocation());
+ Assertions.assertFalse(restored.tableMetadata().properties().containsKey("marker"));
+ Assertions.assertFalse(
+ wrapper.getCatalog().loadTable(copy).properties().containsKey("marker"));
+
+ String otherPointer =
+ wrapper
+ .createTable(
+ ns,
+ CreateTableRequest.builder()
+ .withName("other")
+ .withSchema(metadata.schema())
+ .build())
+ .metadataLocation();
+ var differentUuid =
+ new RegisterTableRequestWithMetadata(
+ ImmutableRegisterTableRequest.builder()
+ .name("copy")
+ .metadataLocation(otherPointer)
+ .overwrite(true)
+ .build(),
+ wrapper.loadTableMetadataFromLocation(otherPointer));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> wrapper.registerTable(ns, differentUuid));
+ Assertions.assertEquals(
+ pointer, wrapper.getTableMetadataLocation(TableIdentifier.of(ns, "copy")).orElseThrow());
+ }
+ }
+
+ /** FileIO that counts metadata input construction without contacting cloud storage. */
+ public static class CountingFileIO extends HadoopFileIO {
+ /** Creates a locally configured FileIO for CatalogUtil's reflective loader. */
+ public CountingFileIO() {
+ super(new Configuration());
+ }
+ /** {@inheritDoc} */
+ @Override
+ public InputFile newInputFile(String path) {
+ READS.incrementAndGet();
+ PATH_READS.computeIfAbsent(path, ignored -> new AtomicInteger()).incrementAndGet();
+ return super.newInputFile(path);
+ }
+ }
+
+ @Test
+ void testCustomCatalogRegistrationHookIsPreserved() throws Exception {
+ CustomJdbcCatalog catalog = Mockito.mock(CustomJdbcCatalog.class);
+ IllegalStateException hook = new IllegalStateException("custom registration hook");
+ Mockito.when(catalog.registerTable(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean()))
+ .thenThrow(hook);
+ try (IcebergCatalogWrapper wrapper =
+ Mockito.spy(
+ new IcebergCatalogWrapper(new IcebergConfig(Map.of("catalog-backend", "memory"))))) {
+ Mockito.doReturn(catalog).when(wrapper).getCatalog();
+ TableMetadata metadata =
+ TableMetadata.newTableMetadata(
+ new Schema(), PartitionSpec.unpartitioned(), "file:/warehouse/table", Map.of());
+ var request =
+ new RegisterTableRequestWithMetadata(
+ ImmutableRegisterTableRequest.builder()
+ .name("table")
+ .metadataLocation("file:/warehouse/table/metadata/v1.metadata.json")
+ .build(),
+ metadata);
+ Assertions.assertSame(
+ hook,
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> wrapper.registerTable(Namespace.of("ns"), request)));
+ Mockito.verify(catalog, Mockito.never())
+ .registerTableWithMetadata(
+ Mockito.any(), Mockito.any(TableMetadata.class), Mockito.anyBoolean());
+ }
+ }
+
+ private static class CustomJdbcCatalog extends JdbcCatalogWithMetadataLocationSupport {
+ private CustomJdbcCatalog() {
+ super(false);
+ }
+ }
+}
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergTableLocationUtils.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergTableLocationUtils.java
new file mode 100644
index 0000000000..c07f91edae
--- /dev/null
+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergTableLocationUtils.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.common.utils;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+class TestIcebergTableLocationUtils {
+ @ParameterizedTest
+ @CsvSource({
+ "s3://b/a,s3://b/a,true",
+ "s3://b/a/,s3://b/a/data,true",
+ "s3://b/a/data,s3://b/a,true",
+ "s3://b/a,s3://b/ab,false",
+ "s3://b/a,s3://other/a,false",
+ "s3a://b/a,s3n://b/a/data,true",
+ "file:///warehouse/a,file:/warehouse/a/data,true",
+ "/warehouse/a,file:///warehouse/a,true",
+ "/warehouse/a:b,file:/warehouse/a:b,true",
+ "s3://b/a%_!,s3://b/ab,false",
+ "file:/warehouse/./a,file:/warehouse/a,true",
+ "file:/warehouse/public/../a,file:/warehouse/a,true",
+ "file:/warehouse//a,file:///warehouse/a,true",
+ "hdfs://namenode/warehouse/./a,hdfs://namenode/warehouse/a,true",
+ "hdfs://namenode/warehouse//a,hdfs://namenode/warehouse/a,true",
+ "s3://b/warehouse/./a,s3://b/warehouse/a,false",
+ "s3://b/warehouse//a,s3://b/warehouse/a,false",
+ "gs://b/warehouse/./a,gs://b/warehouse/a,false"
+ })
+ void testSegmentBoundariesAndAliases(String a, String b, boolean expected) {
+ Assertions.assertEquals(expected, IcebergTableLocationUtils.overlaps(a, b));
+ }
+
+ @Test
+ void testStandardPointerRoot() {
+ Assertions.assertEquals(
+ "s3://b/a",
+ IcebergTableLocationUtils.tableLocation("s3://b/a/metadata/00001-x.metadata.json")
+ .orElseThrow());
+ Assertions.assertTrue(
+ IcebergTableLocationUtils.tableLocation("s3://b/custom/file.json").isEmpty());
+ Assertions.assertTrue(
+ IcebergTableLocationUtils.tableLocation("s3://b/a/metadata/sub/file.json").isEmpty());
+ }
+
+ @Test
+ void testSqlPatternsEscapeWildcardsAndIncludeAliases() {
+ var patterns = IcebergTableLocationUtils.metadataLocationPatterns("s3://b/a_%!/data");
+ Assertions.assertTrue(patterns.contains("s3://b/a!_!%!!/data/%"));
+ Assertions.assertTrue(patterns.contains("s3://b/a!_!%!!/metadata/%"));
+ Assertions.assertTrue(patterns.contains("s3a://b/a!_!%!!/metadata/%"));
+ Assertions.assertTrue(patterns.contains("s3n://b/a!_!%!!/metadata/%"));
+ }
+
+ @Test
+ void testNormalizeAbsentAndRepeatedTrailingSeparators() {
+ Assertions.assertEquals("", IcebergTableLocationUtils.normalize(null));
+ Assertions.assertEquals("s3://b/a", IcebergTableLocationUtils.normalize(" s3://b/a/// "));
+ Assertions.assertEquals(
+ "file:/warehouse/a", IcebergTableLocationUtils.normalize("file:///warehouse/a/"));
+ }
+}
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcMetadataLocationLookup.java b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcMetadataLocationLookup.java
new file mode 100644
index 0000000000..0a57940ba3
--- /dev/null
+++ b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcMetadataLocationLookup.java
@@ -0,0 +1,161 @@
+/*
+ * 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.iceberg.jdbc;
+
+import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.util.Map;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class TestJdbcMetadataLocationLookup {
+ @ParameterizedTest
+ @ValueSource(strings = {"V0", "V1"})
+ void testBulkLookupDoesNotReadMetadataAndFiltersCatalogAndViews(String version, @TempDir Path dir)
+ throws Exception {
+ String uri = "jdbc:sqlite:" + dir.resolve("catalog.db");
+ try (JdbcCatalogWithMetadataLocationSupport catalog =
+ new JdbcCatalogWithMetadataLocationSupport(true)) {
+ catalog.initialize(
+ "main",
+ Map.of(
+ CatalogProperties.URI,
+ uri,
+ CatalogProperties.WAREHOUSE_LOCATION,
+ dir.toString(),
+ "jdbc.schema-version",
+ version));
+ try (Connection connection = DriverManager.getConnection(uri)) {
+ for (int i = 0; i < 2000; i++) {
+ insert(
+ connection,
+ version,
+ "main",
+ "unrelated_" + i,
+ "s3://b/other/t" + i + "/metadata/v1.json",
+ "TABLE");
+ }
+ insert(connection, version, "main", "source", "s3a://b/a_%!/metadata/v1.json", "TABLE");
+ insert(
+ connection, version, "main", "child", "s3://b/a_%!/nested/metadata/v1.json", "TABLE");
+ insert(connection, version, "main", "sibling", "s3://b/aX123!/metadata/v1.json", "TABLE");
+ insert(connection, version, "other", "foreign", "s3://b/a_%!/metadata/v1.json", "TABLE");
+ if (version.equals("V1")) {
+ insert(connection, version, "main", "view", "s3://b/a_%!/metadata/v1.json", "VIEW");
+ }
+ }
+ Map<TableIdentifier, String> candidates =
+ catalog.metadataLocationCandidates("s3://b/a_%!").orElseThrow();
+ Assertions.assertEquals(2, candidates.size());
+ Assertions.assertTrue(candidates.containsKey(TableIdentifier.of("ns", "source")));
+ Assertions.assertTrue(candidates.containsKey(TableIdentifier.of("ns", "child")));
+ Assertions.assertEquals(
+ 1, catalog.metadataLocationCandidates("s3n://b/a_%!/data").orElseThrow().size());
+ Assertions.assertTrue(
+ catalog.metadataLocationCandidates("s3://b/missing").orElseThrow().isEmpty());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"V0", "V1"})
+ void testLookupIncludesFilesystemAliasesAndExactCustomPointer(String version, @TempDir Path dir)
+ throws Exception {
+ String uri = "jdbc:sqlite:" + dir.resolve("catalog.db");
+ try (JdbcCatalogWithMetadataLocationSupport catalog =
+ new JdbcCatalogWithMetadataLocationSupport(true)) {
+ catalog.initialize(
+ "main",
+ Map.of(
+ CatalogProperties.URI,
+ uri,
+ CatalogProperties.WAREHOUSE_LOCATION,
+ dir.toString(),
+ "jdbc.schema-version",
+ version));
+ try (Connection connection = DriverManager.getConnection(uri)) {
+ insert(
+ connection,
+ version,
+ "main",
+ "file_alias",
+ "file:/warehouse/public/../secret/metadata/v1.json",
+ "TABLE");
+ insert(
+ connection,
+ version,
+ "main",
+ "hdfs_alias",
+ "hdfs://node/warehouse//secret/metadata/v1.json",
+ "TABLE");
+ insert(
+ connection, version, "main", "custom", "s3n://b/shared/current.metadata.json", "TABLE");
+ }
+ Assertions.assertTrue(
+ catalog
+ .metadataLocationCandidates("file:/warehouse/secret")
+ .orElseThrow()
+ .containsKey(TableIdentifier.of("ns", "file_alias")));
+ Assertions.assertTrue(
+ catalog
+ .metadataLocationCandidates("hdfs://node/warehouse/secret")
+ .orElseThrow()
+ .containsKey(TableIdentifier.of("ns", "hdfs_alias")));
+ Assertions.assertFalse(
+ catalog
+ .metadataLocationCandidates("s3://b/private")
+ .orElseThrow()
+ .containsKey(TableIdentifier.of("ns", "custom")));
+ Assertions.assertTrue(
+ catalog
+ .metadataLocationCandidates("s3://b/private", "s3a://b/shared/current.metadata.json")
+ .orElseThrow()
+ .containsKey(TableIdentifier.of("ns", "custom")));
+ }
+ }
+
+ private static void insert(
+ Connection connection,
+ String version,
+ String catalog,
+ String table,
+ String pointer,
+ String type)
+ throws Exception {
+ String sql =
+ "INSERT INTO iceberg_tables (catalog_name,table_namespace,table_name,metadata_location"
+ + (version.equals("V1") ? ",iceberg_type" : "")
+ + ") VALUES (?,?,?,?"
+ + (version.equals("V1") ? ",?" : "")
+ + ")";
+ try (PreparedStatement statement = connection.prepareStatement(sql)) {
+ statement.setString(1, catalog);
+ statement.setString(2, "ns");
+ statement.setString(3, table);
+ statement.setString(4, pointer);
+ if (version.equals("V1")) statement.setString(5, type);
+ statement.executeUpdate();
+ }
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
index a293151d98..c93c160226 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
@@ -46,6 +46,7 @@ import org.apache.gravitino.credential.CredentialPropertyUtils;
import org.apache.gravitino.credential.PathBasedCredentialContext;
import org.apache.gravitino.iceberg.common.IcebergConfig;
import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
+import org.apache.gravitino.iceberg.common.ops.RegisterTableRequestWithMetadata;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
import org.apache.gravitino.iceberg.service.cache.ScanPlanCache;
import org.apache.gravitino.iceberg.service.cache.ScanPlanCacheKey;
@@ -909,7 +910,10 @@ public class CatalogWrapperForREST extends IcebergCatalogWrapper {
String currentUuid = super.loadTable(identifier).tableMetadata().uuid();
String newUuid;
try {
- newUuid = loadTableMetadataFromLocation(request.metadataLocation()).uuid();
+ newUuid =
+ request instanceof RegisterTableRequestWithMetadata
+ ? ((RegisterTableRequestWithMetadata) request).tableMetadata().uuid()
+ : loadTableMetadataFromLocation(request.metadataLocation()).uuid();
} catch (RuntimeException e) {
// A metadata file that cannot be read is reported by the register itself.
return;
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java
index 18aa2326d3..acca41577d 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceOperationExecutor.java
@@ -29,6 +29,7 @@ import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import org.apache.gravitino.iceberg.common.ops.RegisterTableRequestWithMetadata;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
@@ -151,10 +152,16 @@ public class IcebergNamespaceOperationExecutor implements IcebergNamespaceOperat
CatalogWrapperForREST catalogWrapper =
icebergCatalogWrapperManager.getCatalogWrapper(context.catalogName());
TableMetadata metadata =
- catalogWrapper.loadTableMetadataFromLocation(registerTableRequest.metadataLocation());
+ registerTableRequest instanceof RegisterTableRequestWithMetadata
+ ? ((RegisterTableRequestWithMetadata) registerTableRequest).tableMetadata()
+ : catalogWrapper.loadTableMetadataFromLocation(registerTableRequest.metadataLocation());
IcebergColumnFieldValidator.validateSchema(metadata.schema());
+ RegisterTableRequest loadedRequest =
+ registerTableRequest instanceof RegisterTableRequestWithMetadata
+ ? registerTableRequest
+ : new RegisterTableRequestWithMetadata(registerTableRequest, metadata);
return catalogWrapper.registerTable(
- namespace, registerTableRequest, context.requestCredentialVending());
+ namespace, loadedRequest, context.requestCredentialVending());
}
@Override
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/RegisterTableSourceResolver.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/RegisterTableSourceResolver.java
index a4ef6aa76d..d8adbce004 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/RegisterTableSourceResolver.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/RegisterTableSourceResolver.java
@@ -20,8 +20,11 @@ package org.apache.gravitino.iceberg.service.dispatcher;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import javax.annotation.Nullable;
import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
+import org.apache.gravitino.iceberg.common.utils.IcebergTableLocationUtils;
import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
@@ -35,12 +38,10 @@ import org.apache.iceberg.exceptions.NoSuchTableException;
* authorization interceptor handlers.
*/
public final class RegisterTableSourceResolver {
-
private RegisterTableSourceResolver() {}
/**
- * Finds tables other than {@code target} that share the given metadata file, UUID, or table
- * location.
+ * Finds tables other than {@code target} whose storage locations overlap the registered table.
*
* @param catalogWrapper catalog to scan
* @param target register destination table
@@ -53,12 +54,57 @@ public final class RegisterTableSourceResolver {
TableIdentifier target,
String metadataLocation,
TableMetadata metadata) {
+ return findOverlappingTables(catalogWrapper, target, metadata.location(), metadataLocation);
+ }
+
+ /**
+ * Finds overlapping tables using a bulk pointer lookup when the backend supports it. Pointer
+ * inference requires the standard {@code <table>/metadata/<file>} layout. Non-JDBC backends
+ * retain namespace discovery. Unreadable metadata propagates the failure instead of bypassing
+ * source authorization.
+ *
+ * @param catalogWrapper catalog to query
+ * @param target destination to exclude
+ * @param location requested table location
+ * @return overlapping live table identities
+ */
+ public static List<TableIdentifier> findOverlappingTables(
+ IcebergCatalogWrapper catalogWrapper, TableIdentifier target, String location) {
+ return findOverlappingTables(catalogWrapper, target, location, null);
+ }
+
+ /** Normalizes path strings so {@code file:/} and {@code file:///} compare equal. */
+ public static String normalizePath(String path) {
+ return IcebergTableLocationUtils.normalize(path);
+ }
+
+ private static List<TableIdentifier> findOverlappingTables(
+ IcebergCatalogWrapper catalogWrapper,
+ TableIdentifier target,
+ String location,
+ @Nullable String metadataLocation) {
List<TableIdentifier> matches = new ArrayList<>();
- String uuid = metadata.uuid();
- String tableLocation = normalizePath(metadata.location());
- String normalizedMeta = normalizePath(metadataLocation);
+ if (normalizePath(location).isEmpty()) {
+ return matches;
+ }
+ Optional<Map<TableIdentifier, String>> candidates =
+ metadataLocation == null
+ ? catalogWrapper.getTableMetadataLocationCandidates(location)
+ : catalogWrapper.getTableMetadataLocationCandidates(location, metadataLocation);
+ if (candidates.isPresent()) {
+ candidates
+ .get()
+ .forEach(
+ (identifier, pointer) -> {
+ if (!identifier.equals(target)
+ && matchesPointer(pointer, location, metadataLocation)) {
+ matches.add(identifier);
+ }
+ });
+ return matches;
+ }
collectMatchingTables(
- catalogWrapper, Namespace.empty(), target, uuid, tableLocation, normalizedMeta, matches);
+ catalogWrapper, Namespace.empty(), target, location, metadataLocation, matches);
return matches;
}
@@ -66,9 +112,8 @@ public final class RegisterTableSourceResolver {
IcebergCatalogWrapper catalogWrapper,
Namespace parent,
TableIdentifier target,
- String uuid,
String tableLocation,
- String metadataLocation,
+ @Nullable String metadataLocation,
List<TableIdentifier> matches) {
List<Namespace> children;
List<TableIdentifier> tables;
@@ -83,13 +128,13 @@ public final class RegisterTableSourceResolver {
}
for (Namespace child : children) {
collectMatchingTables(
- catalogWrapper, child, target, uuid, tableLocation, metadataLocation, matches);
+ catalogWrapper, child, target, tableLocation, metadataLocation, matches);
}
for (TableIdentifier identifier : tables) {
if (identifier.equals(target)) {
continue;
}
- if (matchesSource(catalogWrapper, identifier, uuid, tableLocation, metadataLocation)) {
+ if (matchesSource(catalogWrapper, identifier, tableLocation, metadataLocation)) {
matches.add(identifier);
}
}
@@ -98,47 +143,28 @@ public final class RegisterTableSourceResolver {
private static boolean matchesSource(
IcebergCatalogWrapper catalogWrapper,
TableIdentifier identifier,
- String uuid,
String tableLocation,
- String metadataLocation) {
+ @Nullable String metadataLocation) {
Optional<String> currentMeta = catalogWrapper.getTableMetadataLocation(identifier);
- if (currentMeta.isPresent() && normalizePath(currentMeta.get()).equals(metadataLocation)) {
- return true;
+ if (currentMeta.isPresent()) {
+ return matchesPointer(currentMeta.get(), tableLocation, metadataLocation);
}
try {
TableMetadata existing = catalogWrapper.loadTableMetadata(identifier);
- if (uuid != null && uuid.equals(existing.uuid())) {
- return true;
- }
- return tableLocation != null
- && !tableLocation.isEmpty()
- && tableLocation.equals(normalizePath(existing.location()));
+ return IcebergTableLocationUtils.overlaps(tableLocation, existing.location());
} catch (NoSuchTableException e) {
- // Only a table that no longer exists is unrelated. Any other failure to read its metadata
- // must not be mistaken for unrelated metadata, which would skip source authorization.
return false;
}
}
- /** Normalizes path strings so {@code file:/} and {@code file:///} compare equal. */
- public static String normalizePath(String path) {
- if (path == null) {
- return "";
- }
- String trimmed = path.trim();
- if (trimmed.startsWith("file:")) {
- String withoutScheme = trimmed.substring("file:".length());
- while (withoutScheme.startsWith("//")) {
- withoutScheme = withoutScheme.substring(1);
- }
- if (!withoutScheme.startsWith("/")) {
- withoutScheme = "/" + withoutScheme;
- }
- return "file:" + withoutScheme;
- }
- if (trimmed.endsWith("/")) {
- return trimmed.substring(0, trimmed.length() - 1);
+ private static boolean matchesPointer(
+ String pointer, String location, @Nullable String metadataLocation) {
+ if (metadataLocation != null
+ && normalizePath(pointer).equals(normalizePath(metadataLocation))) {
+ return true;
}
- return trimmed;
+ return IcebergTableLocationUtils.tableLocation(pointer)
+ .map(root -> IcebergTableLocationUtils.overlaps(root, location))
+ .orElse(false);
}
}
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java
index 42239ca17f..9d1c153db4 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java
@@ -185,7 +185,8 @@ public class IcebergTableOperations {
@AuthorizationMetadata(type = Entity.EntityType.CATALOG) @PathParam("prefix") String prefix,
@AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace")
String namespace,
- CreateTableRequest createTableRequest,
+ @IcebergAuthorizationMetadata(type = IcebergAuthorizationMetadata.RequestType.CREATE_TABLE)
+ CreateTableRequest createTableRequest,
@HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,
@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,
@Context UriInfo uriInfo) {
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java
index e5e76caaca..80227dfac1 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/authorization/annotations/IcebergAuthorizationMetadata.java
@@ -34,6 +34,8 @@ public @interface IcebergAuthorizationMetadata {
RENAME_TABLE,
RENAME_VIEW,
CREATE_NAMESPACE,
+ /** A table create, including staged creation, with an optional explicit location. */
+ CREATE_TABLE,
REGISTER_TABLE,
/** A table commit that may complete staged creation. */
UPDATE_TABLE,
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateTableAuthzHandler.java
new file mode 100644
index 0000000000..cdc0e0bf69
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/CreateTableAuthzHandler.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.filter;
+
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CREATE_TABLE_AUTHORIZATION_EXPRESSION;
+
+import java.util.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.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
+
+/** Authorizes the destination schema and every table overlapping an explicit create location. */
+public class CreateTableAuthzHandler implements AuthorizationHandler {
+ private final CreateTableRequest request;
+
+ /**
+ * Creates an authorization handler for an ordinary or staged table create.
+ *
+ * @param request table creation request
+ */
+ public CreateTableAuthzHandler(CreateTableRequest request) {
+ IcebergRESTUtils.validateRequest(request, "CreateTableRequest");
+ this.request = request;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void process(Map<EntityType, NameIdentifier> identifiers) {
+ if (!IcebergTableLocationAuthzHelper.allowed(
+ identifiers, CREATE_TABLE_AUTHORIZATION_EXPRESSION, EntityType.SCHEMA)) {
+ throw new ForbiddenException("Not authorized to create table in the requested schema");
+ }
+ if (request.location() != null) {
+ IcebergTableLocationAuthzHelper.authorizeLocation(
+ identifiers, request.name(), request.location());
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean authorizationCompleted() {
+ return true;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public EntityType entityType() {
+ return EntityType.SCHEMA;
+ }
+}
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 42617eec78..dee5570050 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergMetadataAuthorizationMethodInterceptor.java
@@ -47,6 +47,7 @@ import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.exceptions.BadRequestException;
import org.apache.iceberg.rest.RESTUtil;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
import org.apache.iceberg.rest.requests.UpdateTableRequest;
/**
@@ -187,6 +188,8 @@ public class IcebergMetadataAuthorizationMethodInterceptor
return Optional.of(new RenameViewAuthzHandler(parameters, args));
case CREATE_NAMESPACE:
return Optional.of(new CreateNamespaceAuthzHandler(parameters, args));
+ case CREATE_TABLE:
+ return Optional.of(new CreateTableAuthzHandler((CreateTableRequest) args[i]));
case UPDATE_TABLE:
return Optional.of(new UpdateTableAuthzHandler((UpdateTableRequest) args[i]));
case REGISTER_TABLE:
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergTableLocationAuthzHelper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergTableLocationAuthzHelper.java
new file mode 100644
index 0000000000..aa3080a00d
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/IcebergTableLocationAuthzHelper.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.filter;
+
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_TABLE_AUTHORIZATION_EXPRESSION;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.regex.Pattern;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
+import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
+import org.apache.gravitino.iceberg.service.dispatcher.RegisterTableSourceResolver;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
+import org.apache.gravitino.utils.HierarchicalSchemaUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+
+/** Shared location authorization after destination privileges have been checked. */
+final class IcebergTableLocationAuthzHelper {
+ private static final Pattern SCHEMA_SPLIT =
+ Pattern.compile(Pattern.quote(HierarchicalSchemaUtil.schemaSeparator()));
+
+ private IcebergTableLocationAuthzHelper() {}
+
+ static boolean allowed(
+ Map<EntityType, NameIdentifier> identifiers, String expression, EntityType type) {
+ return new AuthorizationExpressionEvaluator(expression)
+ .evaluate(
+ identifiers,
+ new HashMap<>(),
+ new AuthorizationRequestContext(),
+ Optional.of(type.name()));
+ }
+
+ static void authorizeLocation(
+ Map<EntityType, NameIdentifier> identifiers, String name, String location) {
+ CatalogWrapperForREST wrapper =
+ IcebergRESTServerContext.getInstance()
+ .catalogWrapperManager()
+ .getCatalogWrapper(identifiers.get(EntityType.CATALOG).name());
+ TableIdentifier target =
+ TableIdentifier.of(
+ Namespace.of(SCHEMA_SPLIT.split(identifiers.get(EntityType.SCHEMA).name(), -1)), name);
+ for (TableIdentifier source :
+ RegisterTableSourceResolver.findOverlappingTables(wrapper, target, location)) {
+ requireCanLoadTable(identifiers, source);
+ }
+ }
+
+ static void requireCanLoadTable(
+ Map<EntityType, NameIdentifier> destination, TableIdentifier source) {
+ String metalake = destination.get(EntityType.METALAKE).name();
+ String catalog = destination.get(EntityType.CATALOG).name();
+ String schema =
+ String.join(HierarchicalSchemaUtil.schemaSeparator(), source.namespace().levels());
+ Map<EntityType, NameIdentifier> identifiers = new HashMap<>();
+ identifiers.put(EntityType.METALAKE, NameIdentifierUtil.ofMetalake(metalake));
+ identifiers.put(EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalake, catalog));
+ identifiers.put(EntityType.SCHEMA, NameIdentifierUtil.ofSchema(metalake, catalog, schema));
+ identifiers.put(
+ EntityType.TABLE, NameIdentifierUtil.ofTable(metalake, catalog, schema, source.name()));
+ if (!allowed(identifiers, LOAD_TABLE_AUTHORIZATION_EXPRESSION, EntityType.TABLE)) {
+ throw new ForbiddenException("Not authorized to use the requested table location");
+ }
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
index 0ab300d010..ba565fd63f 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
@@ -18,7 +18,6 @@
*/
package org.apache.gravitino.server.web.filter;
-import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_TABLE_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.MODIFY_TABLE_AUTHORIZATION_EXPRESSION;
import java.lang.reflect.Parameter;
@@ -31,6 +30,7 @@ import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.iceberg.common.ops.RegisterTableRequestWithMetadata;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
import org.apache.gravitino.iceberg.service.dispatcher.RegisterTableSourceResolver;
@@ -131,7 +131,7 @@ public class RegisterTableAuthzHandler implements AuthorizationHandler {
EntityType.TABLE, NameIdentifierUtil.ofTable(metalakeName, catalog, schema, tableName));
requireCanAccessDestination(nameIdentifierMap, request.overwrite());
- authorizeMetadataSources(metalakeName, catalog, schema, tableName, request);
+ authorizeMetadataSources(nameIdentifierMap, catalog, schema, tableName, request);
}
@Override
@@ -166,7 +166,7 @@ public class RegisterTableAuthzHandler implements AuthorizationHandler {
}
private void authorizeMetadataSources(
- String metalakeName,
+ Map<EntityType, NameIdentifier> identifiers,
String catalog,
String schema,
String tableName,
@@ -181,33 +181,13 @@ public class RegisterTableAuthzHandler implements AuthorizationHandler {
RegisterTableSourceResolver.findSourceTables(
catalogWrapper, target, request.metadataLocation(), metadata);
for (TableIdentifier source : sources) {
- requireCanLoadTable(metalakeName, catalog, source);
+ IcebergTableLocationAuthzHelper.requireCanLoadTable(identifiers, source);
}
- }
-
- private static void requireCanLoadTable(
- String metalake, String catalogName, TableIdentifier source) {
- String sourceSchema =
- String.join(HierarchicalSchemaUtil.schemaSeparator(), source.namespace().levels());
- Map<EntityType, NameIdentifier> identifiers = new HashMap<>();
- identifiers.put(EntityType.METALAKE, NameIdentifierUtil.ofMetalake(metalake));
- identifiers.put(EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalake, catalogName));
- identifiers.put(
- EntityType.SCHEMA, NameIdentifierUtil.ofSchema(metalake, catalogName, sourceSchema));
- identifiers.put(
- EntityType.TABLE,
- NameIdentifierUtil.ofTable(metalake, catalogName, sourceSchema, source.name()));
- boolean authorized =
- new AuthorizationExpressionEvaluator(LOAD_TABLE_AUTHORIZATION_EXPRESSION)
- .evaluate(
- identifiers,
- new HashMap<>(),
- new AuthorizationRequestContext(),
- Optional.of(EntityType.TABLE.name()));
- if (!authorized) {
- throw new ForbiddenException(
- "User '%s' is not authorized to register metadata from table '%s'",
- PrincipalUtils.getCurrentUserName(), source);
+ for (int i = 0; i < args.length; i++) {
+ if (args[i] == request) {
+ args[i] = new RegisterTableRequestWithMetadata(request, metadata);
+ break;
+ }
}
}
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java
index 8c34f603f0..3dd983f837 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/UpdateTableAuthzHandler.java
@@ -19,17 +19,15 @@
package org.apache.gravitino.server.web.filter;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CREATE_TABLE_AUTHORIZATION_EXPRESSION;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.MODIFY_TABLE_AUTHORIZATION_EXPRESSION;
-import java.util.HashMap;
import java.util.Map;
-import java.util.Optional;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
-import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor.AuthorizationHandler;
+import org.apache.iceberg.MetadataUpdate;
import org.apache.iceberg.UpdateRequirement;
import org.apache.iceberg.rest.requests.UpdateTableRequest;
@@ -43,6 +41,7 @@ import org.apache.iceberg.rest.requests.UpdateTableRequest;
*/
public class UpdateTableAuthzHandler implements AuthorizationHandler {
private final boolean stagedCreate;
+ private final UpdateTableRequest request;
/**
* Creates a handler using the same staged-create predicate as the table hook dispatcher.
@@ -51,6 +50,7 @@ public class UpdateTableAuthzHandler implements AuthorizationHandler {
*/
public UpdateTableAuthzHandler(UpdateTableRequest request) {
IcebergRESTUtils.validateRequest(request, "UpdateTableRequest");
+ this.request = request;
stagedCreate =
request.requirements().stream()
.anyMatch(UpdateRequirement.AssertTableDoesNotExist.class::isInstance);
@@ -58,23 +58,29 @@ public class UpdateTableAuthzHandler implements AuthorizationHandler {
@Override
public void process(Map<EntityType, NameIdentifier> nameIdentifierMap) {
- if (stagedCreate
- && !new AuthorizationExpressionEvaluator(CREATE_TABLE_AUTHORIZATION_EXPRESSION)
- .evaluate(
- nameIdentifierMap,
- new HashMap<>(),
- new AuthorizationRequestContext(),
- Optional.of(EntityType.SCHEMA.name()))) {
+ String expression =
+ stagedCreate
+ ? CREATE_TABLE_AUTHORIZATION_EXPRESSION
+ : MODIFY_TABLE_AUTHORIZATION_EXPRESSION;
+ if (!IcebergTableLocationAuthzHelper.allowed(nameIdentifierMap, expression, entityType())) {
throw new ForbiddenException(
- "Not authorized to create table in schema '%s'",
- nameIdentifierMap.get(EntityType.SCHEMA));
+ stagedCreate
+ ? "Not authorized to create table in the requested schema"
+ : "Not authorized to modify the requested table");
+ }
+ for (MetadataUpdate update : request.updates()) {
+ if (update instanceof MetadataUpdate.SetLocation) {
+ IcebergTableLocationAuthzHelper.authorizeLocation(
+ nameIdentifierMap,
+ nameIdentifierMap.get(EntityType.TABLE).name(),
+ ((MetadataUpdate.SetLocation) update).location());
+ }
}
}
@Override
public boolean authorizationCompleted() {
- // Ordinary commits continue through the endpoint's existing MODIFY_TABLE expression.
- return stagedCreate;
+ return true;
}
@Override
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
index cd1e548a1c..8d1ef32d06 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.iceberg.service;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
+import java.util.Map;
import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.NotAllowedException;
import javax.ws.rs.NotFoundException;
@@ -27,7 +28,11 @@ import javax.ws.rs.NotSupportedException;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import org.apache.gravitino.exceptions.TokenExpiredException;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
import org.apache.gravitino.server.web.ServerHealth;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.exceptions.AlreadyExistsException;
import org.apache.iceberg.exceptions.BadRequestException;
import org.apache.iceberg.exceptions.CommitFailedException;
@@ -41,10 +46,13 @@ import org.apache.iceberg.exceptions.NotAuthorizedException;
import org.apache.iceberg.exceptions.ServiceUnavailableException;
import org.apache.iceberg.exceptions.UnprocessableEntityException;
import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
import org.apache.iceberg.rest.responses.ErrorResponse;
import org.glassfish.jersey.server.ParamException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
@@ -54,6 +62,44 @@ import software.amazon.awssdk.services.s3.model.S3Exception;
public class TestIcebergExceptionMapper {
private final IcebergExceptionMapper icebergExceptionMapper = new IcebergExceptionMapper();
+ @ParameterizedTest
+ @ValueSource(strings = {"file:///tmp/table", "file:/tmp/table", "/tmp/table", "relative/table"})
+ void testRemoteCatalogLocalLocationReturnsBadRequest(String location) throws Exception {
+ IcebergConfig config =
+ new IcebergConfig(
+ Map.of(
+ "catalog-backend",
+ "jdbc",
+ "warehouse",
+ "s3://bucket/warehouse",
+ "uri",
+ "jdbc:invalid"));
+ try (IcebergCatalogWrapper wrapper = new IcebergCatalogWrapper(config)) {
+ for (boolean staged : new boolean[] {false, true}) {
+ CreateTableRequest.Builder builder =
+ CreateTableRequest.builder()
+ .withName("table")
+ .withSchema(new Schema())
+ .withLocation(location);
+ if (staged) {
+ builder.stageCreate();
+ }
+ CreateTableRequest request = builder.build();
+ BadRequestException failure =
+ Assertions.assertThrows(
+ BadRequestException.class,
+ () -> wrapper.createTable(Namespace.of("namespace"), request));
+ try (Response response = icebergExceptionMapper.toResponse(failure)) {
+ Assertions.assertEquals(400, response.getStatus());
+ ErrorResponse error = (ErrorResponse) response.getEntity();
+ Assertions.assertEquals(400, error.code());
+ Assertions.assertEquals("BadRequestException", error.type());
+ Assertions.assertTrue(error.message().contains(location));
+ }
+ }
+ }
+ }
+
@Test
public void testIcebergExceptionMapper() {
checkExceptionStatus(new IllegalArgumentException(""), 400);
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
index 667b8a99ec..b55b1e493b 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
@@ -20,6 +20,8 @@
package org.apache.gravitino.iceberg.service.dispatcher;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -37,6 +39,7 @@ import java.util.Optional;
import org.apache.gravitino.EntityFieldLimits;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.ops.RegisterTableRequestWithMetadata;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
@@ -288,7 +291,15 @@ public class TestIcebergNamespaceOperationExecutor {
executor.registerTable(mockContext, namespace, request);
verify(mockCatalogWrapper).loadTableMetadataFromLocation(metadataLocation);
- verify(mockCatalogWrapper).registerTable(namespace, request, false);
+ verify(mockCatalogWrapper)
+ .registerTable(
+ eq(namespace),
+ argThat(
+ loaded ->
+ loaded instanceof RegisterTableRequestWithMetadata
+ && ((RegisterTableRequestWithMetadata) loaded).tableMetadata() == metadata
+ && loaded.name().equals(request.name())),
+ eq(false));
}
@Test
@@ -504,4 +515,23 @@ public class TestIcebergNamespaceOperationExecutor {
IcebergRESTServerContext.create(provider, false, false, false, null);
}
}
+
+ @Test
+ void testAuthorizedSnapshotIsNotReadAgain() {
+ Schema schema = new Schema(NestedField.required(1, "id", StringType.get()));
+ TableMetadata metadata =
+ TableMetadata.newTableMetadata(
+ schema, PartitionSpec.unpartitioned(), "file:/tmp/table", Collections.emptyMap());
+ RegisterTableRequestWithMetadata request =
+ new RegisterTableRequestWithMetadata(
+ ImmutableRegisterTableRequest.builder()
+ .name("table")
+ .metadataLocation("file:/tmp/v1.metadata.json")
+ .build(),
+ metadata);
+ Namespace namespace = Namespace.of("ns");
+ executor.registerTable(mockContext, namespace, request);
+ verify(mockCatalogWrapper, never()).loadTableMetadataFromLocation(any());
+ verify(mockCatalogWrapper).registerTable(namespace, request, false);
+ }
}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestJdbcRegisterTableSources.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestJdbcRegisterTableSources.java
new file mode 100644
index 0000000000..44187d3e67
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestJdbcRegisterTableSources.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.iceberg.service.dispatcher;
+
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+class TestJdbcRegisterTableSources {
+ private static final Namespace NAMESPACE = Namespace.of("ns");
+ private static final TableIdentifier SOURCE = TableIdentifier.of(NAMESPACE, "secret");
+ private static final TableIdentifier TARGET = TableIdentifier.of(NAMESPACE, "copy");
+ private static final Schema SCHEMA =
+ new Schema(Types.NestedField.optional(1, "id", Types.LongType.get()));
+
+ @ParameterizedTest
+ @ValueSource(strings = {"./secret", "public/../secret", "/secret", "secret/."})
+ void testFilesystemAliasesMatchLiveTableWithoutMetadataReads(String suffix, @TempDir Path dir)
+ throws Exception {
+ Path warehouse = dir.resolve("warehouse");
+ Files.createDirectories(warehouse.resolve("public"));
+ String root = warehouse.toUri().toString();
+ try (IcebergCatalogWrapper wrapper = newCatalog(dir)) {
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(NAMESPACE).build());
+ var created =
+ wrapper.createTable(
+ NAMESPACE,
+ CreateTableRequest.builder()
+ .withName(SOURCE.name())
+ .withSchema(SCHEMA)
+ .withLocation(root + "secret")
+ .build());
+ String alias = root + suffix;
+ Assertions.assertTrue(
+ Files.isSameFile(
+ Path.of(URI.create(alias)), Path.of(URI.create(created.tableMetadata().location()))));
+ // Model a live pointer written with a filesystem alias by another engine.
+ String aliasedPointer = created.metadataLocation().replace("/metadata/", "/./metadata/");
+ try (Connection connection =
+ DriverManager.getConnection("jdbc:sqlite:" + dir.resolve("catalog.db"));
+ PreparedStatement statement =
+ connection.prepareStatement(
+ "UPDATE iceberg_tables SET metadata_location = ? WHERE table_name = ?")) {
+ statement.setString(1, aliasedPointer);
+ statement.setString(2, SOURCE.name());
+ Assertions.assertEquals(1, statement.executeUpdate());
+ }
+ IcebergCatalogWrapper lookup = Mockito.spy(wrapper);
+ Assertions.assertEquals(
+ List.of(SOURCE),
+ RegisterTableSourceResolver.findOverlappingTables(lookup, TARGET, alias));
+ Mockito.verify(lookup, Mockito.never()).loadTableMetadata(Mockito.any());
+ Mockito.verify(lookup, Mockito.never()).loadTableMetadataFromLocation(Mockito.any());
+ Mockito.verify(lookup, Mockito.never()).listNamespace(Mockito.any());
+ }
+ }
+
+ @Test
+ void testExactCurrentPointerWorksOutsideStandardLayout(@TempDir Path dir) throws Exception {
+ try (IcebergCatalogWrapper wrapper = newCatalog(dir)) {
+ wrapper.createNamespace(CreateNamespaceRequest.builder().withNamespace(NAMESPACE).build());
+ var created =
+ wrapper.createTable(
+ NAMESPACE,
+ CreateTableRequest.builder()
+ .withName(SOURCE.name())
+ .withSchema(SCHEMA)
+ .setProperties(
+ new HashMap<>(
+ Map.of(
+ TableProperties.WRITE_METADATA_LOCATION,
+ dir.resolve("shared_metadata").toUri().toString())))
+ .build());
+ IcebergCatalogWrapper lookup = Mockito.spy(wrapper);
+ Assertions.assertEquals(
+ List.of(SOURCE),
+ RegisterTableSourceResolver.findSourceTables(
+ lookup, TARGET, created.metadataLocation(), created.tableMetadata()));
+ Mockito.verify(lookup, Mockito.never()).loadTableMetadata(Mockito.any());
+ Mockito.verify(lookup, Mockito.never()).loadTableMetadataFromLocation(Mockito.any());
+ Mockito.verify(lookup, Mockito.never()).listNamespace(Mockito.any());
+ }
+ }
+
+ private static IcebergCatalogWrapper newCatalog(Path dir) {
+ return new IcebergCatalogWrapper(
+ new IcebergConfig(
+ Map.of(
+ "catalog-backend",
+ "jdbc",
+ "uri",
+ "jdbc:sqlite:" + dir.resolve("catalog.db"),
+ "jdbc-driver",
+ "org.sqlite.JDBC",
+ "warehouse",
+ dir.resolve("warehouse").toUri().toString())));
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestRegisterTableSourceResolver.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestRegisterTableSourceResolver.java
index aa43395844..9814b47905 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestRegisterTableSourceResolver.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestRegisterTableSourceResolver.java
@@ -18,12 +18,17 @@
*/
package org.apache.gravitino.iceberg.service.dispatcher;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
@@ -31,6 +36,7 @@ import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
import org.apache.iceberg.rest.responses.ListNamespacesResponse;
import org.apache.iceberg.rest.responses.ListTablesResponse;
import org.apache.iceberg.types.Types;
@@ -86,7 +92,7 @@ class TestRegisterTableSourceResolver {
}
@Test
- void testUnreadableSourceMetadataPropagates() {
+ void testStandardPointerDoesNotReadUnreadableMetadata() {
IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
TableIdentifier source = TableIdentifier.of("other", "secret");
stubCatalogWithSource(catalog, source);
@@ -96,11 +102,98 @@ class TestRegisterTableSourceResolver {
.thenReturn(Optional.of("file:/warehouse/other/secret/metadata/v2.metadata.json"));
when(catalog.loadTableMetadata(source)).thenThrow(new RuntimeException("corrupt metadata"));
- Assertions.assertThrows(
- RuntimeException.class,
- () ->
- RegisterTableSourceResolver.findSourceTables(
- catalog, TableIdentifier.of("mine", "copy"), META_LOC, tableMetadata()));
+ Assertions.assertEquals(
+ List.of(source),
+ RegisterTableSourceResolver.findSourceTables(
+ catalog, TableIdentifier.of("mine", "copy"), META_LOC, tableMetadata()));
+ verify(catalog, never()).loadTableMetadata(any());
+ }
+
+ @Test
+ void testBulkPointerLookupAvoidsCatalogWalkAndStorageReads() {
+ IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
+ TableIdentifier target = TableIdentifier.of("mine", "copy");
+ TableIdentifier parent = TableIdentifier.of("other", "parent");
+ TableIdentifier child = TableIdentifier.of("other", "child");
+ TableIdentifier sibling = TableIdentifier.of("other", "sibling");
+ when(catalog.getTableMetadataLocationCandidates("s3://b/a"))
+ .thenReturn(
+ Optional.of(
+ Map.of(
+ parent,
+ "s3://b/metadata/v1.json",
+ child,
+ "s3a://b/a/data/metadata/v1.json",
+ sibling,
+ "s3://b/ab/metadata/v1.json",
+ target,
+ "s3://b/a/metadata/v1.json")));
+ var found = RegisterTableSourceResolver.findOverlappingTables(catalog, target, "s3://b/a");
+ Assertions.assertEquals(Set.of(parent, child), Set.copyOf(found));
+ verify(catalog, never()).listNamespace(any());
+ verify(catalog, never()).listTable(any());
+ verify(catalog, never()).loadTableMetadata(any());
+ verify(catalog, never()).loadTableMetadataFromLocation(any());
+ }
+
+ @Test
+ void testUnreadableFallbackFailsClosed() {
+ IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
+ TableIdentifier source = TableIdentifier.of("other", "secret");
+ stubCatalogWithSource(catalog, source);
+ when(catalog.getTableMetadataLocation(source)).thenReturn(Optional.empty());
+ RuntimeException failure = new RuntimeException("unreadable");
+ when(catalog.loadTableMetadata(source)).thenThrow(failure);
+ Assertions.assertSame(
+ failure,
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ RegisterTableSourceResolver.findOverlappingTables(
+ catalog, TableIdentifier.of("mine", "copy"), TABLE_LOC)));
+ }
+
+ @Test
+ void testDisappearedFallbackSourceIsSkipped() {
+ IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
+ TableIdentifier source = TableIdentifier.of("other", "secret");
+ stubCatalogWithSource(catalog, source);
+ when(catalog.loadTableMetadata(source)).thenThrow(new NoSuchTableException("gone"));
+ Assertions.assertTrue(
+ RegisterTableSourceResolver.findOverlappingTables(
+ catalog, TableIdentifier.of("mine", "copy"), TABLE_LOC)
+ .isEmpty());
+ }
+
+ @Test
+ void testExactCustomPointerStillRequiresSourceAuthorization() {
+ IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
+ TableIdentifier source = TableIdentifier.of("other", "secret");
+ String pointer = "s3://b/shared/custom.metadata.json";
+ when(catalog.getTableMetadataLocationCandidates(TABLE_LOC, pointer))
+ .thenReturn(Optional.of(Map.of(source, pointer)));
+ Assertions.assertEquals(
+ List.of(source),
+ RegisterTableSourceResolver.findSourceTables(
+ catalog, TableIdentifier.of("mine", "copy"), pointer, tableMetadata()));
+ verify(catalog, never()).listNamespace(any());
+ verify(catalog, never()).loadTableMetadata(any());
+ }
+
+ @Test
+ void testSourceIdentityUsesLocationRatherThanUuid() {
+ IcebergCatalogWrapper catalog = mock(IcebergCatalogWrapper.class);
+ TableIdentifier source = TableIdentifier.of("other", "secret");
+ stubCatalogWithSource(catalog, source);
+ TableMetadata existing = tableMetadata();
+ when(catalog.getTableMetadataLocation(source)).thenReturn(Optional.empty());
+ when(catalog.loadTableMetadata(source)).thenReturn(existing);
+ TableMetadata differentLocation =
+ TableMetadata.buildFrom(existing).setLocation("file:/warehouse/unrelated").build();
+ Assertions.assertTrue(
+ RegisterTableSourceResolver.findSourceTables(
+ catalog, TableIdentifier.of("mine", "copy"), META_LOC, differentLocation)
+ .isEmpty());
}
@Test
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
index de5750142d..98dd7c4a0c 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
@@ -42,31 +42,40 @@ import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.iceberg.common.ops.RegisterTableRequestWithMetadata;
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.IcebergNamespaceOperations;
+import org.apache.gravitino.iceberg.service.rest.IcebergTableOperations;
import org.apache.gravitino.listener.EventBus;
import org.apache.gravitino.listener.api.event.BaseEvent;
import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.iceberg.MetadataUpdate;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.UpdateRequirement;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
import org.apache.iceberg.rest.requests.ImmutableRegisterTableRequest;
import org.apache.iceberg.rest.requests.RegisterTableRequest;
+import org.apache.iceberg.rest.requests.UpdateTableRequest;
import org.apache.iceberg.rest.responses.ErrorResponse;
import org.apache.iceberg.rest.responses.ListNamespacesResponse;
import org.apache.iceberg.rest.responses.ListTablesResponse;
import org.apache.iceberg.types.Types;
import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
@@ -241,7 +250,7 @@ class TestRegisterTableAuthzHandler {
}
@Test
- void testUnreadableSourceMetadataBlocksRegister() throws Throwable {
+ void testUnreadableProtectedSourceStillRequiresLoadAccess() throws Throwable {
TableIdentifier source = TableIdentifier.of("other", "secret");
stubCatalogWithSource(source);
when(catalogWrapper.getTableMetadataLocation(source))
@@ -252,6 +261,36 @@ class TestRegisterTableAuthzHandler {
MethodInvocation invocation = registerInvocation(false, "copy", META_LOC);
interceptor.invoke(invocation);
verify(invocation, never()).proceed();
+ verify(catalogWrapper, never()).loadTableMetadata(source);
+ }
+
+ @Test
+ void testUnreadableSourceWithoutPointerNeverReachesOperation() throws Throwable {
+ TableIdentifier source = TableIdentifier.of("other", "secret");
+ stubCatalogWithSource(source);
+ when(catalogWrapper.getTableMetadataLocation(source)).thenReturn(Optional.empty());
+ when(catalogWrapper.loadTableMetadata(source))
+ .thenThrow(new RuntimeException("storage unavailable"));
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ MethodInvocation invocation = registerInvocation(false, "copy", META_LOC);
+ Response response = assertInstanceOf(Response.class, interceptor.invoke(invocation));
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
+ verify(invocation, never()).proceed();
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "file:/warehouse/other/./secret",
+ "file:/warehouse//other/secret",
+ "file:/warehouse/public/../other/secret"
+ })
+ void testFilesystemAliasesCannotBypassCreateAuthorization(String location) throws Throwable {
+ stubCatalogWithSource(TableIdentifier.of("other", "secret"));
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ MethodInvocation invocation = createInvocation(false, location);
+ assertForbidden(interceptor.invoke(invocation));
+ verify(invocation, never()).proceed();
}
@Test
@@ -294,6 +333,126 @@ class TestRegisterTableAuthzHandler {
verify(invocation, never()).proceed();
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testCreateAndStageRequireLoadAccessToOverlappingSource(boolean staged) throws Throwable {
+ stubCatalogWithSource(TableIdentifier.of("other", "secret"));
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ MethodInvocation invocation = createInvocation(staged, TABLE_LOC + "/data");
+ Response response = (Response) interceptor.invoke(invocation);
+ assertForbidden(response);
+ Assertions.assertFalse(((ErrorResponse) response.getEntity()).message().contains("secret"));
+ verify(invocation, never()).proceed();
+ allow(
+ Privilege.Name.USE_CATALOG,
+ Privilege.Name.USE_SCHEMA,
+ Privilege.Name.CREATE_TABLE,
+ Privilege.Name.SELECT_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(createInvocation(staged, TABLE_LOC + "/data")));
+ }
+
+ @Test
+ void testDefaultCreateDoesNotScanAndDeniedCreateDoesNotResolveStorage() throws Throwable {
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA);
+ assertForbidden(interceptor.invoke(createInvocation(false, TABLE_LOC)));
+ verify(catalogWrapper, never()).getTableMetadataLocationCandidates(any());
+ verify(catalogWrapper, never()).listNamespace(any());
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(createInvocation(false, null)));
+ verify(catalogWrapper, never()).getTableMetadataLocationCandidates(any());
+ verify(catalogWrapper, never()).listNamespace(any());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testSetLocationChecksSourceForOrdinaryAndStagedCommits(boolean staged) throws Throwable {
+ stubCatalogWithSource(TableIdentifier.of("other", "secret"));
+ doAnswer(
+ call -> {
+ Privilege.Name privilege = call.getArgument(3);
+ if (privilege == Privilege.Name.MODIFY_TABLE) {
+ MetadataObject object = call.getArgument(2);
+ return object != null
+ && object.type() == MetadataObject.Type.TABLE
+ && object.name().equals("copy");
+ }
+ return Set.of(
+ Privilege.Name.USE_CATALOG,
+ Privilege.Name.USE_SCHEMA,
+ Privilege.Name.CREATE_TABLE)
+ .contains(privilege);
+ })
+ .when(authorizer)
+ .authorize(any(), any(), any(), any(), any());
+ MethodInvocation invocation = locationUpdateInvocation(staged);
+ assertForbidden(interceptor.invoke(invocation));
+ verify(invocation, never()).proceed();
+ allow(
+ Privilege.Name.USE_CATALOG,
+ Privilege.Name.USE_SCHEMA,
+ Privilege.Name.MODIFY_TABLE,
+ Privilege.Name.CREATE_TABLE,
+ Privilege.Name.SELECT_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(locationUpdateInvocation(staged)));
+ }
+
+ @Test
+ void testRegisterRetainsAuthorizedSnapshotForExecution() throws Throwable {
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ MethodInvocation invocation = registerInvocation(false, "copy", META_LOC);
+ assertEquals(PROCEEDED, interceptor.invoke(invocation));
+ RegisterTableRequestWithMetadata request =
+ assertInstanceOf(RegisterTableRequestWithMetadata.class, invocation.getArguments()[2]);
+ assertEquals("copy", request.name());
+ assertEquals(META_LOC, request.metadataLocation());
+ assertEquals(TABLE_LOC, request.tableMetadata().location());
+ verify(catalogWrapper).loadTableMetadataFromLocation(META_LOC);
+ }
+
+ private MethodInvocation createInvocation(boolean staged, String location) throws Throwable {
+ CreateTableRequest.Builder builder =
+ CreateTableRequest.builder().withName("copy").withSchema(tableMetadata().schema());
+ if (location != null) builder.withLocation(location);
+ if (staged) builder.stageCreate();
+ Method method =
+ IcebergTableOperations.class.getMethod(
+ "createTable",
+ String.class,
+ String.class,
+ CreateTableRequest.class,
+ String.class,
+ String.class,
+ UriInfo.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(new Object[] {CATALOG + "/", SCHEMA, builder.build(), null, null, null});
+ when(invocation.proceed()).thenReturn(PROCEEDED);
+ return invocation;
+ }
+
+ private MethodInvocation locationUpdateInvocation(boolean staged) throws Throwable {
+ UpdateTableRequest request =
+ new UpdateTableRequest(
+ staged ? List.of(new UpdateRequirement.AssertTableDoesNotExist()) : List.of(),
+ List.of(new MetadataUpdate.SetLocation(TABLE_LOC + "/data")));
+ Method method =
+ IcebergTableOperations.class.getMethod(
+ "updateTable",
+ String.class,
+ String.class,
+ String.class,
+ UpdateTableRequest.class,
+ String.class,
+ UriInfo.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(new Object[] {CATALOG + "/", SCHEMA, "copy", request, null, null});
+ when(invocation.proceed()).thenReturn(PROCEEDED);
+ return invocation;
+ }
+
private MethodInvocation registerInvocation(
boolean overwrite, String tableName, String metadataLocation) throws Throwable {
RegisterTableRequest request =
diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java
index 044a265482..ec96e0878e 100644
--- a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java
+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java
@@ -40,10 +40,9 @@ public class TrinoIcebergRESTAuthorizationIT extends TrinoIcebergRESTAuthorizati
private static final String ROLE = "trino_role";
- // Substring of the message Gravitino's IRC authorization filter returns in the Iceberg REST 403
- // response (see BaseMetadataAuthorizationMethodInterceptor). Trino surfaces it verbatim for write
- // operations (e.g. CREATE TABLE).
- private static final String NOT_AUTHORIZED_MESSAGE = "is not authorized to perform operation";
+ // Trino preserves the Iceberg REST exception type for denied write operations (e.g. CREATE
+ // TABLE). Match the Forbidden marker independently of each authorization handler's message.
+ private static final String NOT_AUTHORIZED_MESSAGE = "Forbidden:";
// On the read path Trino masks the REST 403 body and only reports that it could not load the
// table/view, so a denied SELECT shows up as this instead of the message above.