Skip to content

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

[#12560] feat(lance): Add table read and list authorization for Lance REST (#12694)

Qi Yud0c656a11a21
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceMetadataFilter.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceMetadataFilter.java
index 0d4b8b80a0..a3043f831b 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceMetadataFilter.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceMetadataFilter.java
@@ -46,4 +46,17 @@ public interface LanceMetadataFilter {
default List<String> filterSchemas(String catalogName, List<String> schemaNames) {
return schemaNames;
}
+
+ /**
+ * Filters the tables listed under a schema.
+ *
+ * @param catalogName the catalog holding the schema.
+ * @param schemaName the schema holding the tables.
+ * @param tableNames the table names to filter.
+ * @return the table names the current caller may see.
+ */
+ default List<String> filterTables(
+ String catalogName, String schemaName, List<String> tableNames) {
+ return tableNames;
+ }
}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
index 69207ba39a..2ca476ed9b 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.CatalogChange;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
@@ -474,12 +475,18 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
String catalogName = nsId.levelAtListPos(0);
Catalog catalog = namespaceWrapper.loadAndValidateLakehouseCatalog(catalogName);
String schemaName = nsId.levelAtListPos(1);
- List<String> tables =
+ // Unauthorized entries are removed before the page is cut, so pagination stays consistent with
+ // what the caller is allowed to see.
+ LanceMetadataFilter metadataFilter = namespaceWrapper.metadataFilter();
+ List<String> tableNames =
Arrays.stream(namespaceWrapper.asTableCatalog(catalog).listTables(Namespace.of(schemaName)))
- .map(ident -> ident.name())
- .sorted()
+ .map(NameIdentifier::name)
.collect(Collectors.toList());
+ List<String> tables =
+ Lists.newArrayList(metadataFilter.filterTables(catalogName, schemaName, tableNames));
+ Collections.sort(tables);
+
PageUtil.Page page = PageUtil.splitPage(tables, pageToken, PageUtil.normalizePageSize(limit));
ListTablesResponse response = new ListTablesResponse();
response.setTables(new LinkedHashSet<>(page.items()));
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationExpressions.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationExpressions.java
index 0ea9dc9131..95de2cdcf6 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationExpressions.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationExpressions.java
@@ -19,15 +19,17 @@
package org.apache.gravitino.lance.service.authorization;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CAN_ACCESS_METADATA;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_SCHEMA_AUTHORIZATION_EXPRESSION;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_TABLE_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.PROBE_SCHEMA_AUTHORIZATION_EXPRESSION;
/**
* Authorization expressions for the Lance REST namespace surface.
*
- * <p>A Lance namespace identifier addresses a Gravitino catalog at one level and a Gravitino schema
- * at two levels, so every expression here selects the privileges to require with an {@code
- * entityType} guard. The interceptor reports the addressed entity type, and an identifier that
- * resolves to any other type matches no branch and is therefore denied.
+ * <p>A Lance identifier carries its depth rather than its kind: one level addresses a Gravitino
+ * catalog, two a schema, and three a table. Every expression here therefore selects the privileges
+ * to require with an {@code entityType} guard. The interceptor reports the addressed entity type,
+ * and an identifier that resolves to any other type matches no branch and is therefore denied.
*/
public final class LanceAuthorizationExpressions {
@@ -69,5 +71,40 @@ public final class LanceAuthorizationExpressions {
(entityType == 'SCHEMA' && (ANY(OWNER, METALAKE, CATALOG) || SCHEMA_OWNER_WITH_USE_CATALOG))
""";
+ /**
+ * Authorizes listing the tables of a namespace. The identifier must address a schema, and the
+ * tables the caller may not see are removed from the listing separately.
+ */
+ public static final String LIST_TABLES_AUTHORIZATION_EXPRESSION =
+ "entityType == 'SCHEMA' && (" + LOAD_SCHEMA_AUTHORIZATION_EXPRESSION + ")";
+
+ /**
+ * Authorizes reading a table. The identifier must address a table, so an identifier that resolves
+ * to a catalog or a schema is denied.
+ */
+ public static final String READ_TABLE_AUTHORIZATION_EXPRESSION =
+ "entityType == 'TABLE' && (" + LOAD_TABLE_AUTHORIZATION_EXPRESSION + ")";
+
+ /**
+ * Authorizes a table existence probe. PROBE_TABLE_LIKE is the privilege that means exactly this,
+ * and CREATE_TABLE is included as well because clients commonly check whether a table exists
+ * immediately before creating it.
+ *
+ * <p>The endpoint answers with an empty 200 or a 404, so the only thing this expression grants is
+ * knowledge of whether the table exists. Reading the table itself stays on {@link
+ * #READ_TABLE_AUTHORIZATION_EXPRESSION}.
+ *
+ * <p>The Gravitino core server reaches the same conclusion by a different route: {@code
+ * loadTable} returns the table body, so it keeps PROBE_TABLE_LIKE out of the primary expression
+ * and admits it through {@code allowCheckExistence}, which only lets the request through when the
+ * table is absent. That machinery is specific to the core interception service, and a dedicated
+ * existence endpoint does not need it.
+ */
+ public static final String PROBE_TABLE_AUTHORIZATION_EXPRESSION =
+ "entityType == 'TABLE' && (("
+ + LOAD_TABLE_AUTHORIZATION_EXPRESSION
+ + ") || (ANY_USE_CATALOG && ANY_USE_SCHEMA"
+ + " && (ANY_PROBE_TABLE_LIKE || ANY_CREATE_TABLE)))";
+
private LanceAuthorizationExpressions() {}
}
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationMetadataFilter.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationMetadataFilter.java
index 2c59b25e38..88de80b777 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationMetadataFilter.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceAuthorizationMetadataFilter.java
@@ -29,7 +29,7 @@ import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.utils.NameIdentifierUtil;
-/** Removes the catalogs and schemas the caller may not see from a Lance listing. */
+/** Removes the catalogs, schemas, and tables the caller may not see from a Lance listing. */
public class LanceAuthorizationMetadataFilter implements LanceMetadataFilter {
private final String metalakeName;
@@ -61,6 +61,15 @@ public class LanceAuthorizationMetadataFilter implements LanceMetadataFilter {
name -> NameIdentifierUtil.ofSchema(metalakeName, catalogName, name));
}
+ @Override
+ public List<String> filterTables(String catalogName, String schemaName, List<String> tableNames) {
+ return filter(
+ tableNames,
+ Entity.EntityType.TABLE,
+ AuthorizationExpressionConstants.FILTER_TABLE_AUTHORIZATION_EXPRESSION,
+ name -> NameIdentifierUtil.ofTable(metalakeName, catalogName, schemaName, name));
+ }
+
private List<String> filter(
List<String> names,
Entity.EntityType entityType,
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceMetadataAuthorizationMethodInterceptor.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceMetadataAuthorizationMethodInterceptor.java
index 3233976bc9..f3acf2f759 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceMetadataAuthorizationMethodInterceptor.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceMetadataAuthorizationMethodInterceptor.java
@@ -39,6 +39,7 @@ import org.apache.gravitino.lance.common.ops.gravitino.CommonUtil;
import org.apache.gravitino.lance.common.ops.gravitino.ObjectIdentifier;
import org.apache.gravitino.lance.service.LanceExceptionMapper;
import org.apache.gravitino.lance.service.authorization.annotations.LanceRootNamespace;
+import org.apache.gravitino.lance.service.rest.LanceTableOperations;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.server.web.filter.BaseMetadataAuthorizationMethodInterceptor;
@@ -53,7 +54,9 @@ import org.lance.namespace.model.CreateNamespaceRequest;
public class LanceMetadataAuthorizationMethodInterceptor
extends BaseMetadataAuthorizationMethodInterceptor implements MethodInterceptor {
+ private static final int CATALOG_NAMESPACE_LEVELS = 1;
private static final int SCHEMA_NAMESPACE_LEVELS = 2;
+ private static final int TABLE_IDENTIFIER_LEVELS = 3;
private final String metalakeName;
@@ -97,21 +100,50 @@ public class LanceMetadataAuthorizationMethodInterceptor
queryArgument(parameters, args, "delimiter")
.orElse(NamespaceWrapper.NAMESPACE_DELIMITER_DEFAULT);
ObjectIdentifier identifier = ObjectIdentifier.of(targetId, Pattern.quote(delimiter));
- if (identifier.levels() == 0 || identifier.levels() > SCHEMA_NAMESPACE_LEVELS) {
+ if (identifier.levels() == 0 || identifier.levels() > maxIdentifierLevels(method)) {
throw unsupportedIdentifier(targetId);
}
+ // A Lance identifier carries its depth rather than its kind, so the addressed entity type
+ // follows from the level count: one level is a catalog, two a schema, three a table. An
+ // identifier of the wrong depth for an operation matches no branch of that operation's
+ // expression and is therefore denied rather than silently authorized against another type.
Map<Entity.EntityType, NameIdentifier> identifiers = baseIdentifiers();
String catalogName = identifier.levelAtListPos(0);
identifiers.put(
Entity.EntityType.CATALOG, NameIdentifierUtil.ofCatalog(metalakeName, catalogName));
+ if (identifier.levels() == CATALOG_NAMESPACE_LEVELS) {
+ return new AuthorizationTarget(identifiers, Entity.EntityType.CATALOG);
+ }
+
+ String schemaName = identifier.levelAtListPos(1);
+ identifiers.put(
+ Entity.EntityType.SCHEMA,
+ NameIdentifierUtil.ofSchema(metalakeName, catalogName, schemaName));
if (identifier.levels() == SCHEMA_NAMESPACE_LEVELS) {
- identifiers.put(
- Entity.EntityType.SCHEMA,
- NameIdentifierUtil.ofSchema(metalakeName, catalogName, identifier.levelAtListPos(1)));
return new AuthorizationTarget(identifiers, Entity.EntityType.SCHEMA);
}
- return new AuthorizationTarget(identifiers, Entity.EntityType.CATALOG);
+
+ identifiers.put(
+ Entity.EntityType.TABLE,
+ NameIdentifierUtil.ofTable(
+ metalakeName, catalogName, schemaName, identifier.levelAtListPos(2)));
+ return new AuthorizationTarget(identifiers, Entity.EntityType.TABLE);
+ }
+
+ /**
+ * Returns the deepest identifier the given operation can address. Only the table resource accepts
+ * a table identifier; every namespace operation stops at a schema, so a deeper identifier is
+ * rejected as unsupported before any expression sees it. Anything else falls back to the
+ * shallower bound, so a resource added later cannot widen its own reach by omission.
+ *
+ * @param method invoked protocol method
+ * @return the maximum number of levels the operation's identifier may carry
+ */
+ private static int maxIdentifierLevels(Method method) {
+ return LanceTableOperations.class.isAssignableFrom(method.getDeclaringClass())
+ ? TABLE_IDENTIFIER_LEVELS
+ : SCHEMA_NAMESPACE_LEVELS;
}
/**
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceRESTAuthInterceptionService.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceRESTAuthInterceptionService.java
index 18b18cc51a..ae10436f69 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceRESTAuthInterceptionService.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/authorization/LanceRESTAuthInterceptionService.java
@@ -30,6 +30,7 @@ import javax.inject.Named;
import org.aopalliance.intercept.ConstructorInterceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.gravitino.lance.service.rest.LanceNamespaceOperations;
+import org.apache.gravitino.lance.service.rest.LanceTableOperations;
import org.glassfish.hk2.api.Descriptor;
import org.glassfish.hk2.api.Filter;
import org.glassfish.hk2.api.InterceptionService;
@@ -40,8 +41,12 @@ public class LanceRESTAuthInterceptionService implements InterceptionService {
/** HK2 binding name for the metalake passed to the authorization interceptor. */
public static final String METALAKE_BINDING = "lanceAuthorizationMetalake";
+ // Membership here only routes a class through the interceptor; each method still opts in with
+ // @AuthorizationExpression, and a method without one runs unauthorized. The table writes
+ // (create, register, drop, alter) are still to be annotated.
private static final Set<String> INTERCEPTED_CLASSES =
- ImmutableSet.of(LanceNamespaceOperations.class.getName());
+ ImmutableSet.of(
+ LanceNamespaceOperations.class.getName(), LanceTableOperations.class.getName());
private final MethodInterceptor authorizationInterceptor;
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
index 0001ec6ce9..0b5a769f8e 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.lance.service.rest;
import static org.apache.gravitino.lance.common.ops.NamespaceWrapper.NAMESPACE_DELIMITER_DEFAULT;
import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.CREATE_NAMESPACE_AUTHORIZATION_EXPRESSION;
+import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.LIST_TABLES_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.MODIFY_NAMESPACE_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.PROBE_NAMESPACE_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.CAN_ACCESS_METADATA;
@@ -189,6 +190,7 @@ public class LanceNamespaceOperations {
@Path("{id}/table/list")
@Timed(name = "list-tables." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "list-tables", absolute = true)
+ @AuthorizationExpression(expression = LIST_TABLES_AUTHORIZATION_EXPRESSION)
public Response listTables(
@PathParam("id") String namespaceId,
@DefaultValue(NAMESPACE_DELIMITER_DEFAULT) @QueryParam("delimiter") String delimiter,
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
index 5279f9cadd..268a73e314 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
@@ -22,6 +22,8 @@ import static org.apache.gravitino.lance.common.ops.NamespaceWrapper.NAMESPACE_D
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_LOCATION;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_LOCATION_HEADER;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_PROPERTIES_PREFIX_HEADER;
+import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.PROBE_TABLE_AUTHORIZATION_EXPRESSION;
+import static org.apache.gravitino.lance.service.authorization.LanceAuthorizationExpressions.READ_TABLE_AUTHORIZATION_EXPRESSION;
import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
@@ -49,6 +51,7 @@ import org.apache.gravitino.lance.common.utils.LancePropertiesUtils;
import org.apache.gravitino.lance.common.utils.SerializationUtils;
import org.apache.gravitino.lance.service.LanceExceptionMapper;
import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.lance.namespace.errors.TableNotFoundException;
import org.lance.namespace.model.AlterColumnsEntry;
import org.lance.namespace.model.AlterTableAlterColumnsRequest;
@@ -84,6 +87,7 @@ public class LanceTableOperations {
@Path("/describe")
@Timed(name = "describe-table." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "describe-table", absolute = true)
+ @AuthorizationExpression(expression = READ_TABLE_AUTHORIZATION_EXPRESSION)
public Response describeTable(
@PathParam("id") String tableId,
@DefaultValue(NAMESPACE_DELIMITER_DEFAULT) @QueryParam("delimiter") String delimiter,
@@ -232,6 +236,7 @@ public class LanceTableOperations {
@Path("/exists")
@Timed(name = "table-exists." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "table-exists", absolute = true)
+ @AuthorizationExpression(expression = PROBE_TABLE_AUTHORIZATION_EXPRESSION)
public Response tableExists(
@PathParam("id") String tableId,
@QueryParam("delimiter") @DefaultValue("$") String delimiter,
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceNamespaceListFiltering.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceNamespaceListFiltering.java
index 5ec17d1358..63a6c090e1 100644
--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceNamespaceListFiltering.java
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceNamespaceListFiltering.java
@@ -22,10 +22,14 @@ import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.gravitino.Catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
import org.apache.gravitino.lance.common.ops.LanceMetadataFilter;
+import org.apache.gravitino.rel.TableCatalog;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.ListTablesResponse;
import org.mockito.Mockito;
/** Verifies that unauthorized namespaces never consume a slot in the returned page. */
@@ -33,6 +37,7 @@ class TestGravitinoLanceNamespaceListFiltering {
private static final String DELIMITER = Pattern.quote("$");
private static final String CATALOG = "b_catalog";
+ private static final String SCHEMA = "b_schema";
@Test
void testCatalogsAreFilteredBeforePagination() {
@@ -70,6 +75,35 @@ class TestGravitinoLanceNamespaceListFiltering {
Assertions.assertEquals(Set.of("b_schema"), response.getNamespaces());
}
+ @Test
+ void testTablesAreFilteredBeforePagination() {
+ GravitinoLanceNamespaceWrapper wrapper = Mockito.mock(GravitinoLanceNamespaceWrapper.class);
+ Catalog catalog = catalog(CATALOG);
+ Mockito.when(wrapper.loadAndValidateLakehouseCatalog(CATALOG)).thenReturn(catalog);
+ TableCatalog tableCatalog = Mockito.mock(TableCatalog.class);
+ Mockito.when(wrapper.asTableCatalog(catalog)).thenReturn(tableCatalog);
+ Mockito.when(tableCatalog.listTables(Namespace.of(SCHEMA)))
+ .thenReturn(
+ new NameIdentifier[] {
+ NameIdentifier.of(SCHEMA, "a_table"), NameIdentifier.of(SCHEMA, "b_table")
+ });
+ // "a_table" sorts first, so it would fill the single-entry page if it were filtered after
+ // pagination.
+ Mockito.doReturn(allowOnly("b_table")).when(wrapper).metadataFilter();
+
+ ListTablesResponse response =
+ new GravitinoLanceNameSpaceOperations(wrapper)
+ .listTables(CATALOG + "$" + SCHEMA, "$", null, 1);
+
+ Assertions.assertEquals(Set.of("b_table"), Set.copyOf(response.getTables()));
+
+ Mockito.when(wrapper.metadataFilter()).thenReturn(LanceMetadataFilter.NOOP);
+ response =
+ new GravitinoLanceNameSpaceOperations(wrapper)
+ .listTables(CATALOG + "$" + SCHEMA, "$", null, 10);
+ Assertions.assertEquals(Set.of("a_table", "b_table"), Set.copyOf(response.getTables()));
+ }
+
@Test
void testNullFilterRestoresNoop() {
GravitinoLanceNamespaceWrapper wrapper = new GravitinoLanceNamespaceWrapper();
@@ -91,6 +125,8 @@ class TestGravitinoLanceNamespaceListFiltering {
.thenAnswer(invocation -> retain(invocation.getArgument(0), allowedName));
Mockito.when(filter.filterSchemas(Mockito.anyString(), Mockito.anyList()))
.thenAnswer(invocation -> retain(invocation.getArgument(1), allowedName));
+ Mockito.when(filter.filterTables(Mockito.anyString(), Mockito.anyString(), Mockito.anyList()))
+ .thenAnswer(invocation -> retain(invocation.getArgument(2), allowedName));
return filter;
}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java
new file mode 100644
index 0000000000..785439b678
--- /dev/null
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java
@@ -0,0 +1,256 @@
+/*
+ * 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.lance.integration.test;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.List;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.auth.AuthConstants;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.integration.test.util.BaseIT;
+import org.apache.gravitino.server.web.ObjectMapperProvider;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.lance.namespace.model.CreateNamespaceRequest;
+import org.lance.namespace.model.ListTablesResponse;
+import org.lance.namespace.model.RegisterTableRequest;
+
+/** Verifies that read-only Lance REST table operations are authorized and filtered. */
+public class LanceTableAuthorizationIT extends BaseIT {
+
+ private static final String ADMIN = "lance_table_authz_admin";
+ private static final String READER = "lance_table_authz_reader";
+ private static final String PROBER = "lance_table_authz_prober";
+ private static final String CATALOG = "lance_table_authz_catalog";
+ private static final String SCHEMA = "lance_table_authz_schema";
+
+ // The hidden table sorts first so that a listing filtered after pagination rather than before it
+ // would return an empty first page instead of the visible table.
+ private static final String HIDDEN_TABLE = "a_hidden_table";
+ private static final String VISIBLE_TABLE = "b_visible_table";
+ private static final String MISSING_TABLE = "c_missing_table";
+ private static final String DELIMITER = ".";
+
+ @TempDir private static Path tempDir;
+
+ private final HttpClient httpClient = HttpClient.newHttpClient();
+
+ @BeforeAll
+ public void startIntegrationTest() throws Exception {
+ ignoreLanceAuxRestService = false;
+ customConfigs.put(Configs.ENABLE_AUTHORIZATION.getKey(), "true");
+ customConfigs.put(Configs.SERVICE_ADMINS.getKey(), ADMIN);
+ customConfigs.put(Configs.AUTHENTICATORS.getKey(), "simple");
+ customConfigs.put("SimpleAuthUserName", ADMIN);
+ super.startIntegrationTest();
+
+ String metalakeName = getLanceRESTServerMetalakeName();
+ client.createMetalake(metalakeName, "Lance table authorization tests", null);
+ GravitinoMetalake metalake = client.loadMetalake(metalakeName);
+ metalake.addUser(READER);
+ metalake.addUser(PROBER);
+
+ createNamespace(CATALOG);
+ createNamespace(id(CATALOG, SCHEMA));
+ registerTable(VISIBLE_TABLE);
+ registerTable(HIDDEN_TABLE);
+
+ SecurableObject catalogScope = SecurableObjects.ofCatalog(CATALOG, new ArrayList<>());
+ SecurableObject schemaScope =
+ SecurableObjects.ofSchema(catalogScope, SCHEMA, new ArrayList<>());
+
+ // The reader may select exactly one table, so the other one must stay invisible even though
+ // the reader can reach the schema holding it.
+ grant(
+ metalake,
+ "lance_table_authz_reader_role",
+ READER,
+ List.of(
+ SecurableObjects.ofCatalog(
+ CATALOG, new ArrayList<>(List.of(Privileges.UseCatalog.allow()))),
+ SecurableObjects.ofSchema(
+ catalogScope, SCHEMA, new ArrayList<>(List.of(Privileges.UseSchema.allow()))),
+ SecurableObjects.ofTable(
+ schemaScope,
+ VISIBLE_TABLE,
+ new ArrayList<>(List.of(Privileges.SelectTable.allow())))));
+
+ grant(
+ metalake,
+ "lance_table_authz_prober_role",
+ PROBER,
+ List.of(
+ SecurableObjects.ofCatalog(
+ CATALOG, new ArrayList<>(List.of(Privileges.UseCatalog.allow()))),
+ SecurableObjects.ofSchema(
+ catalogScope,
+ SCHEMA,
+ new ArrayList<>(
+ List.of(Privileges.UseSchema.allow(), Privileges.CreateTable.allow())))));
+ }
+
+ @AfterAll
+ public void clean() throws Exception {
+ try {
+ if (client != null) {
+ client.dropMetalake(getLanceRESTServerMetalakeName(), true);
+ }
+ } finally {
+ super.stopIntegrationTest();
+ }
+ }
+
+ @Test
+ public void testTableReadRequiresTablePrivileges() throws Exception {
+ assertStatus(200, table(READER, VISIBLE_TABLE, "describe"));
+ assertStatus(200, table(READER, VISIBLE_TABLE, "exists"));
+
+ HttpResponse<String> denied = table(READER, HIDDEN_TABLE, "describe");
+ assertStatus(403, denied);
+ // A denied describe must not leak the table location or any other stored property.
+ Assertions.assertFalse(denied.body().contains(location(HIDDEN_TABLE)), denied.body());
+ assertStatus(403, table(READER, HIDDEN_TABLE, "exists"));
+
+ assertStatus(200, table(ADMIN, HIDDEN_TABLE, "describe"));
+ }
+
+ @Test
+ public void testCreateTablePrivilegeProbesButDoesNotRead() throws Exception {
+ // Clients probe before creating, so CREATE_TABLE authorizes the probe but not a read.
+ assertStatus(200, table(PROBER, VISIBLE_TABLE, "exists"));
+ assertStatus(403, table(PROBER, VISIBLE_TABLE, "describe"));
+ }
+
+ @Test
+ public void testInaccessibleAndMissingTablesAreIndistinguishable() throws Exception {
+ // Both are forbidden for the reader, so the endpoint cannot be used to probe for existence.
+ assertStatus(403, table(READER, HIDDEN_TABLE, "describe"));
+ assertStatus(403, table(READER, MISSING_TABLE, "describe"));
+
+ // The privileged caller does see the difference.
+ assertStatus(200, table(ADMIN, HIDDEN_TABLE, "describe"));
+ assertStatus(404, table(ADMIN, MISSING_TABLE, "describe"));
+ }
+
+ @Test
+ public void testTablesAreFilteredBeforePagination() throws Exception {
+ Assertions.assertEquals(List.of(VISIBLE_TABLE), listTables(READER, 1));
+ Assertions.assertEquals(List.of(VISIBLE_TABLE), listTables(READER, 10));
+ Assertions.assertEquals(List.of(HIDDEN_TABLE, VISIBLE_TABLE), listTables(ADMIN, 10));
+ }
+
+ private List<String> listTables(String user, int limit) throws Exception {
+ HttpRequest request =
+ request(user, "/v1/namespace/" + id(CATALOG, SCHEMA) + "/table/list", "&limit=" + limit)
+ .GET()
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ assertStatus(200, response);
+ List<String> tables =
+ new ArrayList<>(
+ ObjectMapperProvider.objectMapper()
+ .readValue(response.body(), ListTablesResponse.class)
+ .getTables());
+ tables.sort(String::compareTo);
+ return tables;
+ }
+
+ private void grant(
+ GravitinoMetalake metalake, String role, String user, List<SecurableObject> objects) {
+ metalake.createRole(role, new HashMap<>(), objects);
+ metalake.grantRolesToUser(List.of(role), user);
+ }
+
+ private String id(String... levels) {
+ return String.join(DELIMITER, levels);
+ }
+
+ private String location(String tableName) {
+ return tempDir.resolve(tableName).toString() + "/";
+ }
+
+ private void createNamespace(String namespaceId) throws Exception {
+ CreateNamespaceRequest body = new CreateNamespaceRequest();
+ for (String level : namespaceId.split("\\" + DELIMITER)) {
+ body.addIdItem(level);
+ }
+ assertStatus(200, send(ADMIN, "/v1/namespace/" + namespaceId + "/create", body));
+ }
+
+ private void registerTable(String tableName) throws Exception {
+ RegisterTableRequest body = new RegisterTableRequest();
+ body.setId(List.of(CATALOG, SCHEMA, tableName));
+ body.setLocation(location(tableName));
+ assertStatus(
+ 200, send(ADMIN, "/v1/table/" + id(CATALOG, SCHEMA, tableName) + "/register", body));
+ }
+
+ private HttpResponse<String> table(String user, String tableName, String operation)
+ throws Exception {
+ HttpRequest request =
+ request(user, "/v1/table/" + id(CATALOG, SCHEMA, tableName) + "/" + operation, "")
+ .POST(HttpRequest.BodyPublishers.ofString("{}"))
+ .build();
+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ }
+
+ private HttpResponse<String> send(String user, String path, Object body) throws Exception {
+ HttpRequest request =
+ request(user, path, "")
+ .POST(
+ HttpRequest.BodyPublishers.ofString(
+ ObjectMapperProvider.objectMapper().writeValueAsString(body)))
+ .build();
+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ }
+
+ private HttpRequest.Builder request(String user, String path, String extraQuery) {
+ String credentials =
+ Base64.getEncoder().encodeToString((user + ":dummy").getBytes(StandardCharsets.UTF_8));
+ return HttpRequest.newBuilder()
+ .uri(
+ URI.create(
+ String.format(
+ "http://localhost:%d/lance%s?delimiter=%s%s",
+ getLanceRESTServerPort(), path, DELIMITER, extraQuery)))
+ .header(
+ AuthConstants.HTTP_HEADER_AUTHORIZATION,
+ AuthConstants.AUTHORIZATION_BASIC_HEADER + credentials)
+ .header(AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER, "ALL")
+ .header("Content-Type", "application/json");
+ }
+
+ private void assertStatus(int expected, HttpResponse<String> response) {
+ Assertions.assertEquals(expected, response.statusCode(), "Unexpected body: " + response.body());
+ }
+}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/authorization/TestLanceMetadataAuthorizationMethodInterceptor.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/authorization/TestLanceMetadataAuthorizationMethodInterceptor.java
index 1f41e7bc30..ffd30bb338 100644
--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/authorization/TestLanceMetadataAuthorizationMethodInterceptor.java
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/authorization/TestLanceMetadataAuthorizationMethodInterceptor.java
@@ -32,6 +32,7 @@ import java.lang.reflect.Method;
import java.util.Set;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.gravitino.UserPrincipal;
@@ -40,6 +41,7 @@ import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.lance.service.authorization.annotations.LanceRootNamespace;
import org.apache.gravitino.lance.service.rest.LanceNamespaceOperations;
+import org.apache.gravitino.lance.service.rest.LanceTableOperations;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -47,8 +49,10 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.lance.namespace.model.CreateNamespaceRequest;
+import org.lance.namespace.model.DescribeTableRequest;
import org.lance.namespace.model.DropNamespaceRequest;
import org.lance.namespace.model.ErrorResponse;
+import org.lance.namespace.model.TableExistsRequest;
import org.mockito.MockedStatic;
/** Tests the Lance-specific target resolution and response mapping around the shared pipeline. */
@@ -57,6 +61,7 @@ class TestLanceMetadataAuthorizationMethodInterceptor {
private static final String METALAKE = "test_metalake";
private static final String CATALOG = "test_catalog";
private static final String SCHEMA = "test_schema";
+ private static final String TABLE = "test_table";
private static final String PROCEEDED = "PROCEEDED";
private GravitinoAuthorizer authorizer;
@@ -133,6 +138,8 @@ class TestLanceMetadataAuthorizationMethodInterceptor {
@Test
void testProtocolAndOperationFailuresUseLanceResponses() throws Throwable {
+ // A namespace operation stops at a schema, so a table identifier is not merely unauthorized
+ // there, it is not a namespace at all and is rejected before any expression is evaluated.
MethodInvocation invalid =
invocation(namespaceMethod("describeNamespace"), CATALOG + "$" + SCHEMA + "$extra", "$");
assertErrorResponse(interceptor.invoke(invalid), Response.Status.BAD_REQUEST);
@@ -234,6 +241,106 @@ class TestLanceMetadataAuthorizationMethodInterceptor {
verify(dropSchema, never()).proceed();
}
+ @Test
+ void testTableReadRequiresTablePrivileges() throws Throwable {
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.SELECT_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(describeTableInvocation(tableId())));
+ assertEquals(PROCEEDED, interceptor.invoke(tableExistsInvocation(tableId())));
+
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.MODIFY_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(describeTableInvocation(tableId())));
+
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA);
+ MethodInvocation describe = describeTableInvocation(tableId());
+ assertErrorResponse(interceptor.invoke(describe), Response.Status.FORBIDDEN);
+ verify(describe, never()).proceed();
+ }
+
+ @Test
+ void testCreateTablePrivilegeProbesButDoesNotRead() throws Throwable {
+ // Clients probe for a table right before creating it, so CREATE_TABLE authorizes the probe.
+ // It must not expose the table schema or properties through describe.
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.CREATE_TABLE);
+ assertEquals(PROCEEDED, interceptor.invoke(tableExistsInvocation(tableId())));
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(tableId())), Response.Status.FORBIDDEN);
+ }
+
+ @Test
+ void testProbeTableLikePrivilegeProbesButDoesNotRead() throws Throwable {
+ // PROBE_TABLE_LIKE is the privilege that means "may learn whether this exists", so it carries
+ // the existence endpoint. It must not reach describe, which returns the table itself.
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.PROBE_TABLE_LIKE);
+ assertEquals(PROCEEDED, interceptor.invoke(tableExistsInvocation(tableId())));
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(tableId())), Response.Status.FORBIDDEN);
+ }
+
+ @Test
+ void testDenyOverridesTablePrivileges() throws Throwable {
+ allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, Privilege.Name.SELECT_TABLE);
+ when(authorizer.deny(any(), any(), any(), any(), any())).thenReturn(true);
+
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(tableId())), Response.Status.FORBIDDEN);
+ assertErrorResponse(
+ interceptor.invoke(tableExistsInvocation(tableId())), Response.Status.FORBIDDEN);
+ }
+
+ @Test
+ void testTableExpressionsRejectIdentifiersOfTheWrongDepth() throws Throwable {
+ when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(true);
+ allow(Privilege.Name.values());
+
+ // A catalog or schema identifier must not be authorized as if it addressed a table, on either
+ // the read expression or the wider probe expression.
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(CATALOG)), Response.Status.FORBIDDEN);
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(CATALOG + "$" + SCHEMA)),
+ Response.Status.FORBIDDEN);
+ assertErrorResponse(
+ interceptor.invoke(tableExistsInvocation(CATALOG)), Response.Status.FORBIDDEN);
+ assertErrorResponse(
+ interceptor.invoke(tableExistsInvocation(CATALOG + "$" + SCHEMA)),
+ Response.Status.FORBIDDEN);
+ assertErrorResponse(
+ interceptor.invoke(describeTableInvocation(tableId() + "$extra")),
+ Response.Status.BAD_REQUEST);
+
+ // The bound is per resource: the namespace resource does not accept a table identifier at all,
+ // so listTables rejects it rather than authorizing it against the table it names.
+ assertErrorResponse(
+ interceptor.invoke(listTablesInvocation(tableId())), Response.Status.BAD_REQUEST);
+
+ assertEquals(PROCEEDED, interceptor.invoke(listTablesInvocation(CATALOG + "$" + SCHEMA)));
+ }
+
+ private String tableId() {
+ return CATALOG + "$" + SCHEMA + "$" + TABLE;
+ }
+
+ private MethodInvocation describeTableInvocation(String tableId) throws Throwable {
+ Method method =
+ LanceTableOperations.class.getMethod(
+ "describeTable", String.class, String.class, Boolean.class, DescribeTableRequest.class);
+ return invocation(method, tableId, "$", null, new DescribeTableRequest());
+ }
+
+ private MethodInvocation tableExistsInvocation(String tableId) throws Throwable {
+ Method method =
+ LanceTableOperations.class.getMethod(
+ "tableExists", String.class, String.class, HttpHeaders.class, TableExistsRequest.class);
+ return invocation(method, tableId, "$", null, new TableExistsRequest());
+ }
+
+ private MethodInvocation listTablesInvocation(String namespaceId) throws Throwable {
+ Method method =
+ LanceNamespaceOperations.class.getMethod(
+ "listTables", String.class, String.class, String.class, Integer.class);
+ return invocation(method, namespaceId, "$", null, null);
+ }
+
private MethodInvocation createInvocation(String namespaceId, String delimiter, String mode)
throws Throwable {
Method method =