This is an automated email from the ASF dual-hosted git repository. github-actions[bot] pushed a commit to branch cherry-pick-6b73de4f-to-branch-1.3 in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit a0d7c18af66a223cc73777d7995ef8959cdca874 Author: roryqi <[email protected]> AuthorDate: Wed Nov 11 16:10:58 2026 +0800 [#14823] fix: Correct catalog authentication and metadata authorization (#14827) ### What changes were proposed in this pull request? - Key HMS client pools by effective/real principal, authentication method, and Hive authentication settings. Fresh proxy UGIs and renewed delegation tokens reuse a pool; explicitly configured UGI keys retain their existing behavior. - Keep `toMetadataObject` strict and explicitly use `toMetadataObjectForRead` for existing legacy tag/policy authorization, owners, relation reads, and cleanup. Manager create/rename checks reject dotted new names before writes. - Report unreadable Ranger service-lookup responses with configuration context while preserving service-not-found handling. - Clear the MyBatis local cache at full-role get/list boundaries so ID-bound privilege names reflect committed parent renames at READ_COMMITTED. Acquire the session before entering its cleanup block. ### Why are the changes needed? HMS connections retain their original identity, legacy dotted names can block API access and cleanup, and non-JSON Ranger responses lack useful error context. Session-cached SQL results can also keep function securable names stale after parent renames. Fixes #14823 ### Does this PR introduce _any_ user-facing change? Yes. New dotted tag/policy names are rejected before persistence, authorized operations on existing dotted names work, Ranger errors include useful context, and full-role responses refresh privilege names. No REST API or configuration keys are added. Functions retain the shared parent-ID read path. The cross-node entity-cache invalidation window also affects tables and views and is outside this PR's scope. ### How was this patch tested? - Full core unit suite: 2,859 tests (2 skipped); full H2 lane: 734 tests (1 skipped). Zero failures. - MySQL and PostgreSQL: 18 focused tests on each backend cover legacy dotted-name owners/relation reads and role privilege refresh after peer renames. - Regression coverage checks session-acquisition failure cleanup, cached function parent-ID get/list routing, rejection of tag/policy association targets, and dotted-name create/rename rejection through the event/hook/manager chain. - Existing Hive coverage checks reuse across fresh proxy UGIs/token renewal and isolation across real users/authentication settings; REST and authorization tests cover legacy-object recovery. - Spotless and `git diff --check` pass. Full deployed multi-server and Kerberos integration suites were not run. # Conflicts: # core/src/main/java/org/apache/gravitino/storage/relational/service/OwnerMetaService.java # core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java # core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java # core/src/main/java/org/apache/gravitino/tag/TagManager.java # core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java # core/src/test/java/org/apache/gravitino/tag/TestTagManager.java # server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java # server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionEvaluator.java # server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java --- .../ranger/RangerClientExtension.java | 24 ++ .../ranger/TestRangerClientExtension.java | 36 ++- .../authorization/AuthorizationUtils.java | 4 +- .../org/apache/gravitino/policy/PolicyManager.java | 4 + .../relational/service/OwnerMetaService.java | 28 +++ .../relational/service/RoleMetaService.java | 26 ++- .../storage/relational/service/TagMetaService.java | 80 ++++++- .../storage/relational/utils/SessionUtils.java | 27 +++ .../java/org/apache/gravitino/tag/TagManager.java | 17 ++ .../apache/gravitino/utils/NameIdentifierUtil.java | 31 +++ .../apache/gravitino/policy/TestPolicyManager.java | 50 ++++ .../service/TestFunctionPrivilegeCoherence.java | 253 +++++++++++++++++++++ .../relational/service/TestOwnerMetaService.java | 49 ++++ .../service/TestPOStorageReadRouting.java | 24 ++ .../relational/service/TestRoleMetaService.java | 25 ++ .../relational/service/TestTagMetaService.java | 187 +++++++++++++++ .../storage/relational/session/TestSqlSession.java | 27 +++ .../org/apache/gravitino/tag/TestTagManager.java | 65 ++++++ .../gravitino/utils/TestNameIdentifierUtil.java | 49 ++++ .../common/utils/IcebergHiveCachedClientPool.java | 26 +++ .../utils/TestIcebergHiveCachedClientPool.java | 119 ++++++++++ .../server/authorization/MetadataAuthzHelper.java | 8 + .../AuthorizationExpressionEvaluator.java | 12 + .../authorization/jcasbin/JcasbinAuthorizer.java | 6 +- .../authorization/TestMetadataAuthzHelper.java | 32 +++ .../jcasbin/TestJcasbinAuthorizer.java | 196 ++++++++++++++++ 26 files changed, 1397 insertions(+), 8 deletions(-) diff --git a/authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtension.java b/authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtension.java index 383b6cc6b7..f63cd2bd5c 100644 --- a/authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtension.java +++ b/authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtension.java @@ -20,6 +20,7 @@ package org.apache.gravitino.authorization.ranger; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; +import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.UniformInterfaceException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -31,9 +32,11 @@ import org.apache.gravitino.authorization.ranger.reference.VXGroup; import org.apache.gravitino.authorization.ranger.reference.VXGroupList; import org.apache.gravitino.authorization.ranger.reference.VXUser; import org.apache.gravitino.authorization.ranger.reference.VXUserList; +import org.apache.gravitino.exceptions.AuthorizationPluginException; import org.apache.ranger.RangerClient; import org.apache.ranger.RangerServiceException; import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -91,6 +94,27 @@ public class RangerClientExtension extends RangerClient { } } + /** + * Looks up a service and reports invalid Ranger Admin responses with configuration context. + * + * @param serviceName the Ranger service name + * @return the Ranger service + * @throws RangerServiceException if Ranger returns a valid API error + * @throws AuthorizationPluginException if the response cannot be read + */ + @Override + public RangerService getService(String serviceName) throws RangerServiceException { + try { + return super.getService(serviceName); + } catch (ClientHandlerException e) { + throw new AuthorizationPluginException( + e, + "Failed to read Ranger Admin response for service '%s'. Check the configured Ranger " + + "Admin URL, connectivity, and proxy settings; the service lookup must return JSON.", + serviceName); + } + } + @Override public RangerPolicy createPolicy(RangerPolicy policy) throws RangerServiceException { Preconditions.checkArgument( diff --git a/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/TestRangerClientExtension.java b/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/TestRangerClientExtension.java index 1d9971a657..75286f61c2 100644 --- a/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/TestRangerClientExtension.java +++ b/authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/TestRangerClientExtension.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; @@ -40,6 +41,7 @@ import org.apache.gravitino.authorization.ranger.reference.VXGroup; import org.apache.gravitino.authorization.ranger.reference.VXGroupList; import org.apache.gravitino.authorization.ranger.reference.VXUser; import org.apache.gravitino.authorization.ranger.reference.VXUserList; +import org.apache.gravitino.exceptions.AuthorizationPluginException; import org.apache.ranger.RangerServiceException; import org.apache.ranger.plugin.model.RangerPolicy; import org.junit.jupiter.api.AfterEach; @@ -97,7 +99,7 @@ public class TestRangerClientExtension { } }); server.createContext( - "/public/v2/api/service/name/", + "/service/public/v2/api/service/name/", exchange -> respond(exchange, 404, "{\"statusCode\":1,\"msgDesc\":\"not found\"}")); server.createContext( "/service/public/v2/api/policy", @@ -179,6 +181,38 @@ public class TestRangerClientExtension { Assertions.assertEquals(11L, created.getId()); } + /** Non-JSON responses are contextualized without changing service-not-found errors. */ + @Test + public void testNonJsonServiceResponseIsActionable() throws Exception { + for (int status : new int[] {200, 404}) { + server.removeContext("/service/public/v2/api/service/name/"); + server.createContext( + "/service/public/v2/api/service/name/", + exchange -> { + byte[] body = "upstream unavailable".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "text/plain"); + exchange.sendResponseHeaders(status, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + if (status == 200) { + AuthorizationPluginException error = + Assertions.assertThrows( + AuthorizationPluginException.class, () -> client.getService("hive-service")); + Assertions.assertTrue(error.getMessage().contains("hive-service")); + Assertions.assertTrue(error.getMessage().contains("must return JSON")); + Assertions.assertInstanceOf(ClientHandlerException.class, error.getCause()); + } else { + RangerServiceException error = + Assertions.assertThrows( + RangerServiceException.class, () -> client.getService("hive-service")); + Assertions.assertEquals(status, error.getStatus().getStatusCode()); + Assertions.assertTrue(error.getMessage().contains("upstream unavailable")); + } + } + } + @Test public void testServiceNotFoundStatus() { RangerServiceException e = diff --git a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java index ec1ea7fe7c..7adf02d3bc 100644 --- a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java +++ b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java @@ -339,7 +339,7 @@ public class AuthorizationUtils { // authorization plugin. if (GravitinoEnv.getInstance().internalAccessControlDispatcher() != null) { notifyEntityNameIdMappingChange(ident, type); - MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(ident, type); + MetadataObject metadataObject = NameIdentifierUtil.toMetadataObjectForRead(ident, type); String metalake = type == Entity.EntityType.METALAKE ? ident.name() : ident.namespace().level(0); @@ -400,7 +400,7 @@ public class AuthorizationUtils { // authorization plugin. if (GravitinoEnv.getInstance().internalAccessControlDispatcher() != null) { notifyEntityNameIdMappingChange(ident, type); - MetadataObject oldMetadataObject = NameIdentifierUtil.toMetadataObject(ident, type); + MetadataObject oldMetadataObject = NameIdentifierUtil.toMetadataObjectForRead(ident, type); MetadataObject newMetadataObject = NameIdentifierUtil.toMetadataObject(newIdent, type); MetadataObjectChange renameChange = diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java index 0e9f14349d..fc4ab95635 100644 --- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java +++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java @@ -140,6 +140,8 @@ public class PolicyManager implements PolicyDispatcher { boolean enabled, PolicyContent content) throws PolicyAlreadyExistsException { + NameIdentifierUtil.checkMetadataObjectName( + NameIdentifierUtil.ofPolicy(metalake, policyName), Entity.EntityType.POLICY); NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake); checkMetalake(metalakeIdent, entityStore); return TreeLockUtils.doWithTreeLock( @@ -492,6 +494,8 @@ public class PolicyManager implements PolicyDispatcher { for (PolicyChange change : changes) { if (change instanceof PolicyChange.RenamePolicy) { newName = ((PolicyChange.RenamePolicy) change).getNewName(); + NameIdentifierUtil.checkMetadataObjectName( + NameIdentifier.of(policyEntity.namespace(), newName), Entity.EntityType.POLICY); } else if (change instanceof PolicyChange.UpdatePolicyComment) { newComment = ((PolicyChange.UpdatePolicyComment) change).getNewComment(); } else if (change instanceof PolicyChange.UpdateContent) { diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/OwnerMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/OwnerMetaService.java index 2b261e35b3..270fa736e9 100644 --- a/core/src/main/java/org/apache/gravitino/storage/relational/service/OwnerMetaService.java +++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/OwnerMetaService.java @@ -183,7 +183,20 @@ public class OwnerMetaService { OwnerRelPO ownerRelPO = POConverters.initializeOwnerRelPOsWithVersion( metalakeId, ownerType.name(), ownerId, entityType.name(), entityId); +<<<<<<< HEAD SessionUtils.doMultipleWithCommit( +======= + String metadataObjectType = + NameIdentifierUtil.toMetadataObjectForRead(entity, entityType).type().name(); + assignOwner( + metalake, + metalakeId, + owner, + ownerType, + ownerId, + List.of(entityId), + entityType, +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) () -> SessionUtils.doWithoutCommit( OwnerMetaMapper.class, @@ -221,11 +234,26 @@ public class OwnerMetaService { List<OwnerRelForDeletion> deletions = new ArrayList<>(ownedObjects.size()); List<OwnerRelPO> ownerRelPOs = new ArrayList<>(ownedObjects.size()); for (NameIdentifier entity : ownedObjects) { +<<<<<<< HEAD Long entityId = EntityIdService.getEntityId(entity, ownedObjectType); deletions.add( new OwnerRelForDeletion( entityId, NameIdentifierUtil.toMetadataObject(entity, ownedObjectType).type().name())); +======= + entityIds.add(EntityIdService.getEntityId(entity, ownedObjectType)); + } + entityIds.sort(Comparator.naturalOrder()); + String metadataObjectType = + NameIdentifierUtil.toMetadataObjectForRead(ownedObjects.get(0), ownedObjectType) + .type() + .name(); + + List<OwnerRelForDeletion> deletions = new ArrayList<>(entityIds.size()); + List<OwnerRelPO> ownerRelPOs = new ArrayList<>(entityIds.size()); + for (Long entityId : entityIds) { + deletions.add(new OwnerRelForDeletion(entityId, metadataObjectType)); +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) ownerRelPOs.add( POConverters.initializeOwnerRelPOsWithVersion( metalakeId, ownerType.name(), ownerId, ownedObjectType.name(), entityId)); diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java index 38358942e4..b20c0ddedc 100644 --- a/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java +++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java @@ -119,14 +119,28 @@ public class RoleMetaService { NameIdentifier metadataObjectIdent, Entity.EntityType metadataObjectType, boolean allFields) { String metalake = NameIdentifierUtil.getMetalake(metadataObjectIdent); MetadataObject metadataObject = - NameIdentifierUtil.toMetadataObject(metadataObjectIdent, metadataObjectType); + NameIdentifierUtil.toMetadataObjectForRead(metadataObjectIdent, metadataObjectType); long metadataObjectId = EntityIdService.getEntityId(metadataObjectIdent, metadataObjectType); List<RolePO> rolePOs = +<<<<<<< HEAD SessionUtils.getWithoutCommit( RoleMetaMapper.class, mapper -> mapper.listRolesByMetadataObjectIdAndType( metadataObjectId, metadataObject.type().name())); +======= + allFields + ? SessionUtils.getWithoutCommitFresh( + RoleMetaMapper.class, + mapper -> + mapper.listRolesWithPrivilegesByMetadataObjectIdAndType( + metadataObjectId, metadataObject.type().name())) + : SessionUtils.getWithoutCommit( + RoleMetaMapper.class, + mapper -> + mapper.listRolesByMetadataObjectIdAndType( + metadataObjectId, metadataObject.type().name())); +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) return rolePOs.stream() .map( po -> { @@ -448,9 +462,19 @@ public class RoleMetaService { private static RolePO getRolePOByMetalakeIdAndName(Long metalakeId, String roleName) { RolePO rolePO = +<<<<<<< HEAD SessionUtils.getWithoutCommit( RoleMetaMapper.class, mapper -> mapper.selectRoleMetaByMetalakeIdAndName(metalakeId, roleName)); +======= + withPrivileges + ? SessionUtils.getWithoutCommitFresh( + RoleMetaMapper.class, + mapper -> mapper.selectRoleWithPrivilegesByMetalakeIdAndName(metalakeId, roleName)) + : SessionUtils.getWithoutCommit( + RoleMetaMapper.class, + mapper -> mapper.selectRoleMetaByMetalakeIdAndName(metalakeId, roleName)); +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) if (rolePO == null) { throw new NoSuchEntityException( diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java index 0e7e356916..2ff9466b64 100644 --- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java +++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java @@ -202,7 +202,8 @@ public class TagMetaService { public List<TagEntity> listTagsForMetadataObject( NameIdentifier objectIdent, Entity.EntityType objectType) throws NoSuchTagException, IOException { - MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(objectIdent, objectType); + MetadataObject metadataObject = + NameIdentifierUtil.toMetadataObjectForRead(objectIdent, objectType); String metalake = objectIdent.namespace().level(0); List<TagPO> tagPOs = null; @@ -220,9 +221,83 @@ public class TagMetaService { throw e; } +<<<<<<< HEAD return tagPOs.stream() .map(tagPO -> POConverters.fromTagPO(tagPO, NamespaceUtil.ofTag(metalake))) .collect(Collectors.toList()); +======= + return tagPOsToTagEntities(tagPOs, NamespaceUtil.ofTag(metalake)); + } + + /** + * Lists direct tag assignments for metadata objects of one type in one metalake. + * + * @param objectIdentifiers source identifiers + * @param objectType source entity type + * @return tag relation edges with their source identifiers + */ + public List<RelationalEntity<?>> listTagsForMetadataObjects( + List<NameIdentifier> objectIdentifiers, Entity.EntityType objectType) { + if (objectIdentifiers.isEmpty()) { + return new ArrayList<>(); + } + String metalake = objectIdentifiers.get(0).namespace().level(0); + Map<Long, NameIdentifier> identifiersById = new LinkedHashMap<>(); + Map<NameIdentifier, List<NameIdentifier>> columnsByTable = new LinkedHashMap<>(); + for (NameIdentifier identifier : objectIdentifiers) { + Preconditions.checkArgument( + metalake.equals(identifier.namespace().level(0)), + "All metadata objects must belong to the same metalake"); + if (objectType == Entity.EntityType.COLUMN) { + columnsByTable + .computeIfAbsent( + NameIdentifier.of(identifier.namespace().levels()), ignored -> new ArrayList<>()) + .add(identifier); + } else { + identifiersById.put(EntityIdService.getEntityId(identifier, objectType), identifier); + } + } + columnsByTable.forEach( + (table, columns) -> { + Long tableId = EntityIdService.getEntityId(table, Entity.EntityType.TABLE); + Map<String, Long> ids = + TableColumnMetaService.getInstance() + .getColumnIdsByTableIdAndNames( + tableId, + columns.stream().map(NameIdentifier::name).collect(Collectors.toList())); + columns.forEach(column -> identifiersById.put(ids.get(column.name()), column)); + }); + List<TagRelationTagPO> rows = new ArrayList<>(); + String metadataObjectType = + NameIdentifierUtil.toMetadataObjectForRead(objectIdentifiers.get(0), objectType) + .type() + .toString(); + for (List<Long> batch : Lists.partition(new ArrayList<>(identifiersById.keySet()), 500)) { + rows.addAll( + SessionUtils.getWithoutCommit( + TagMetadataObjectRelMapper.class, + mapper -> mapper.listTagPOsByMetadataObjectIdsAndType(batch, metadataObjectType))); + } + Map<Long, List<TagPO>> rowsByObject = new LinkedHashMap<>(); + rows.forEach( + row -> + rowsByObject + .computeIfAbsent(row.getMetadataObjectId(), ignored -> new ArrayList<>()) + .add(row)); + List<RelationalEntity<?>> result = new ArrayList<>(); + rowsByObject.forEach( + (id, tagRows) -> + tagPOsToTagEntities(tagRows, NamespaceUtil.ofTag(metalake)) + .forEach( + tag -> + result.add( + new RelationalEntity<>( + SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL, + identifiersById.get(id), + objectType, + tag)))); + return result; +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) } @Monitored( @@ -231,7 +306,8 @@ public class TagMetaService { public TagEntity getTagForMetadataObject( NameIdentifier objectIdent, Entity.EntityType objectType, NameIdentifier tagIdent) throws NoSuchEntityException, IOException { - MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(objectIdent, objectType); + MetadataObject metadataObject = + NameIdentifierUtil.toMetadataObjectForRead(objectIdent, objectType); String metalake = objectIdent.namespace().level(0); TagPO tagPO = null; diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java index 8a36bc1add..9b4d4747dc 100644 --- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java +++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.function.Consumer; import java.util.function.Function; import org.apache.gravitino.storage.relational.session.SqlSessions; +import org.apache.ibatis.session.SqlSession; /** * This class provides utility methods to perform database operations with MyBatis mappers in the @@ -76,6 +77,32 @@ public class SessionUtils { } } + /** + * Performs a read after clearing the current session's local query cache. + * + * <p>Use at full-role authorization read boundaries so subsequent ID-to-name queries observe peer + * commits at READ_COMMITTED. Clearing applies to all local query results in the shared session, + * including reads cached earlier by an enclosing write transaction. Previously cached reads may + * therefore execute again. The operation uses the same connection without committing or rolling + * back; uncommitted writes, JDBC isolation, and session ownership are preserved. Other reads + * continue to use the default session cache between fresh-read boundaries. + * + * @param mapperClazz the mapper class + * @param func the read operation + * @param <T> the mapper type + * @param <R> the result type + * @return the read result + */ + public static <T, R> R getWithoutCommitFresh(Class<T> mapperClazz, Function<T, R> func) { + SqlSession session = SqlSessions.getSqlSession(); + try { + session.clearCache(); + return getWithoutCommit(mapperClazz, func); + } finally { + SqlSessions.closeSqlSession(); + } + } + /** * Performs a database operation without a commit. Can be used standalone or nested within other * transactions. This method is for operations that do not return a result. diff --git a/core/src/main/java/org/apache/gravitino/tag/TagManager.java b/core/src/main/java/org/apache/gravitino/tag/TagManager.java index 812b6e00e1..bb3d32a16e 100644 --- a/core/src/main/java/org/apache/gravitino/tag/TagManager.java +++ b/core/src/main/java/org/apache/gravitino/tag/TagManager.java @@ -109,6 +109,21 @@ public class TagManager implements TagDispatcher { public Tag createTag(String metalake, String name, String comment, Map<String, String> properties) throws TagAlreadyExistsException { +<<<<<<< HEAD +======= + return createTag(metalake, name, comment, properties, TagValueConstraint.anyValue()); + } + + public Tag createTag( + String metalake, + String name, + String comment, + Map<String, String> properties, + TagValueConstraint valueConstraint) + throws TagAlreadyExistsException { + NameIdentifierUtil.checkMetadataObjectName( + NameIdentifierUtil.ofTag(metalake, name), Entity.EntityType.TAG); +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) Map<String, String> tagProperties = properties == null ? Collections.emptyMap() : properties; checkMetalake(NameIdentifier.of(metalake), entityStore); @@ -403,6 +418,8 @@ public class TagManager implements TagDispatcher { for (TagChange change : changes) { if (change instanceof TagChange.RenameTag) { newName = ((TagChange.RenameTag) change).getNewName(); + NameIdentifierUtil.checkMetadataObjectName( + NameIdentifier.of(tagEntity.namespace(), newName), Entity.EntityType.TAG); } else if (change instanceof TagChange.UpdateTagComment) { newComment = ((TagChange.UpdateTagComment) change).getNewComment(); } else if (change instanceof TagChange.SetProperty) { diff --git a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java index 33747d8b44..c64a335b86 100644 --- a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java +++ b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java @@ -616,6 +616,9 @@ public class NameIdentifierUtil { * Convert the given {@link NameIdentifier} and {@link Entity.EntityType} to {@link * MetadataObject}. * + * <p>All object types reject dots in their names. Use {@link #toMetadataObjectForRead} when + * addressing an existing tag or policy with a legacy dotted name. + * * @param ident The identifier * @param entityType The entity type * @return The converted {@link MetadataObject} @@ -703,6 +706,34 @@ public class NameIdentifierUtil { } } + /** + * Converts an existing identifier for reads, authorization, and cleanup. + * + * <p>Only tag and policy names accept legacy dots: these are single-level metadata objects with + * no parent scope. Namespace checks still apply, and all other types use strict conversion. New + * names and rename targets must use {@link #toMetadataObject} instead. + * + * @param ident the existing metadata object's identifier + * @param entityType the entity type + * @return the converted metadata object + * @throws IllegalArgumentException if the identifier or type is invalid + */ + public static MetadataObject toMetadataObjectForRead( + NameIdentifier ident, Entity.EntityType entityType) { + Preconditions.checkArgument( + ident != null && entityType != null, "The identifier and entity type must not be null"); + switch (entityType) { + case TAG: + checkTag(ident); + return MetadataObjects.of(null, ident.name(), MetadataObject.Type.TAG); + case POLICY: + checkPolicy(ident); + return MetadataObjects.of(null, ident.name(), MetadataObject.Type.POLICY); + default: + return toMetadataObject(ident, entityType); + } + } + /** * Get the metalake name of the given {@link NameIdentifier}. * diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java index fced5fc92b..c11a2f1353 100644 --- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java +++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java @@ -75,6 +75,9 @@ import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException; import org.apache.gravitino.exceptions.PolicyAlreadyExistsException; import org.apache.gravitino.function.FunctionDefinition; import org.apache.gravitino.function.FunctionType; +import org.apache.gravitino.hook.PolicyHookDispatcher; +import org.apache.gravitino.listener.EventBus; +import org.apache.gravitino.listener.PolicyEventDispatcher; import org.apache.gravitino.lock.LockManager; import org.apache.gravitino.meta.AuditInfo; import org.apache.gravitino.meta.BaseMetalake; @@ -371,6 +374,53 @@ public class TestPolicyManager { Assertions.assertEquals("Metalake non_existent_metalake does not exist", e.getMessage()); } + /** Invalid create/rename requests must never persist an unaddressable policy. */ + @Test + public void testRejectDottedNameBeforeWrite() throws IOException { + PolicyDispatcher dispatcher = + new PolicyEventDispatcher(new EventBus(List.of()), new PolicyHookDispatcher(policyManager)); + PolicyContent content = PolicyContents.custom(Map.of("rule", 1), SUPPORTS_OBJECT_TYPES, null); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + dispatcher.createPolicy( + METALAKE, "invalid.policy", Policy.BuiltInType.CUSTOM, null, true, content)); + Assertions.assertFalse( + entityStore.exists( + NameIdentifierUtil.ofPolicy(METALAKE, "invalid.policy"), Entity.EntityType.POLICY)); + PolicyEntity original = createCustomPolicy(METALAKE, "valid_policy", content); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + dispatcher.alterPolicy( + METALAKE, original.name(), PolicyChange.rename("invalid.policy"))); + Assertions.assertEquals(original, policyManager.getPolicy(METALAKE, original.name())); + Assertions.assertFalse( + entityStore.exists( + NameIdentifierUtil.ofPolicy(METALAKE, "invalid.policy"), Entity.EntityType.POLICY)); + } + + /** Legacy policy names can be listed and deleted without bypassing their stored identity. */ + @Test + public void testLegacyDottedPolicyRecovery() throws IOException { + PolicyEntity legacy = + PolicyEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName("legacy.policy") + .withNamespace(NameIdentifierUtil.ofPolicy(METALAKE, "legacy.policy").namespace()) + .withPolicyType(Policy.BuiltInType.CUSTOM) + .withEnabled(true) + .withContent(PolicyContents.custom(Map.of("rule", 1), SUPPORTS_OBJECT_TYPES, null)) + .withAuditInfo( + AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build()) + .build(); + entityStore.put(legacy, false); + Assertions.assertEquals(legacy.name(), policyManager.getPolicy(METALAKE, legacy.name()).name()); + Assertions.assertTrue( + Arrays.asList(policyManager.listPolicies(METALAKE)).contains(legacy.name())); + Assertions.assertTrue(policyManager.deletePolicy(METALAKE, legacy.name())); + } + @Test public void testAlterPolicy() { String policyName = "policy1" + UUID.randomUUID().toString().replace("-", ""); diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionPrivilegeCoherence.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionPrivilegeCoherence.java new file mode 100644 index 0000000000..eaac265f53 --- /dev/null +++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionPrivilegeCoherence.java @@ -0,0 +1,253 @@ +/* + * 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.storage.relational.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.apache.gravitino.Config; +import org.apache.gravitino.Entity; +import org.apache.gravitino.GravitinoEnv; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.Namespace; +import org.apache.gravitino.authorization.AuthorizationUtils; +import org.apache.gravitino.authorization.Privileges; +import org.apache.gravitino.authorization.SecurableObjects; +import org.apache.gravitino.cache.CachedEntityIdResolver; +import org.apache.gravitino.cache.CaffeineEntityCache; +import org.apache.gravitino.meta.CatalogEntity; +import org.apache.gravitino.meta.FunctionEntity; +import org.apache.gravitino.meta.RoleEntity; +import org.apache.gravitino.meta.SchemaEntity; +import org.apache.gravitino.storage.RandomIdGenerator; +import org.apache.gravitino.storage.relational.RelationalEntityStoreIdResolver; +import org.apache.gravitino.storage.relational.TestJDBCBackend; +import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper; +import org.apache.gravitino.storage.relational.po.CatalogPO; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.gravitino.storage.relational.utils.SessionUtils; +import org.apache.ibatis.session.LocalCacheScope; +import org.apache.ibatis.session.SqlSession; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +/** Verifies function grant names against parent renames committed by a separate node. */ +public class TestFunctionPrivilegeCoherence extends TestJDBCBackend { + + private static final String METALAKE = "function_coherence_ml"; + private static final String CATALOG = "function_catalog"; + private static final String SCHEMA = "function_schema"; + + private CatalogEntity catalog; + private SchemaEntity schema; + private FunctionEntity function; + private RoleEntity role; + + /** Creates a function and an ID-bound grant before the reader cache is warmed. */ + @BeforeEach + public void prepare() throws Exception { + createAndInsertMakeLake(METALAKE); + catalog = createAndInsertCatalog(METALAKE, CATALOG); + schema = createAndInsertSchema(METALAKE, CATALOG, SCHEMA); + function = + createFunctionEntity( + RandomIdGenerator.INSTANCE.nextId(), + Namespace.of(METALAKE, CATALOG, SCHEMA), + "function", + AUDIT_INFO); + backend.insert(function, false); + role = + createRoleEntity( + RandomIdGenerator.INSTANCE.nextId(), + AuthorizationUtils.ofRoleNamespace(METALAKE), + "function_role", + AUDIT_INFO, + List.of( + SecurableObjects.parse( + CATALOG + "." + SCHEMA + ".function", + MetadataObject.Type.FUNCTION, + List.of(Privileges.ExecuteFunction.allow()))), + Map.of()); + backend.insert(role, false); + } + + /** Peer renames must be visible to repeated role reads in a READ_COMMITTED session. */ + @TestTemplate + public void testPeerParentRenamesRefreshFunctionSecurableNames() throws Exception { + checkPeerParentRenames(false); + } + + /** Listing full roles also refreshes parent names without a preceding get-role call. */ + @TestTemplate + public void testPeerParentRenamesRefreshListedFunctionSecurableNames() throws Exception { + checkPeerParentRenames(true); + } + + /** Queries outside full-role authorization reads still reuse the MyBatis session cache. */ + @TestTemplate + public void testUnrelatedQueriesRetainSessionCaching() { + try (SqlSession session = + SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession()) { + assertEquals(LocalCacheScope.SESSION, session.getConfiguration().getLocalCacheScope()); + CatalogMetaMapper mapper = session.getMapper(CatalogMetaMapper.class); + CatalogPO first = mapper.selectCatalogMetaById(catalog.id()); + assertEquals(CATALOG, first.getCatalogName()); + assertSame(first, mapper.selectCatalogMetaById(catalog.id())); + session.clearCache(); + assertNotSame(first, mapper.selectCatalogMetaById(catalog.id())); + } + } + + private void checkPeerParentRenames(boolean listRoles) throws Exception { + withReaderCache( + () -> { + SessionUtils.beginTransaction(); + try { + assertFunctionGrantName(CATALOG + "." + SCHEMA + ".function", listRoles); + onPeer( + () -> + backend.update( + catalog.nameIdentifier(), + Entity.EntityType.CATALOG, + entity -> + CatalogEntity.builder() + .withId(catalog.id()) + .withName("renamed_catalog") + .withNamespace(catalog.namespace()) + .withType(catalog.getType()) + .withProvider(catalog.getProvider()) + .withComment(catalog.getComment()) + .withProperties(catalog.getProperties()) + .withAuditInfo(AUDIT_INFO) + .build())); + assertFunctionGrantName("renamed_catalog." + SCHEMA + ".function", listRoles); + onPeer( + () -> + backend.update( + NameIdentifier.of(METALAKE, "renamed_catalog", SCHEMA), + Entity.EntityType.SCHEMA, + entity -> + SchemaEntity.builder() + .withId(schema.id()) + .withName("renamed_schema") + .withNamespace(Namespace.of(METALAKE, "renamed_catalog")) + .withProperties(schema.properties()) + .withComment(schema.comment()) + .withAuditInfo(AUDIT_INFO) + .build())); + assertFunctionGrantName("renamed_catalog.renamed_schema.function", listRoles); + FunctionEntity loaded = + FunctionMetaService.getInstance() + .getFunctionByIdentifier( + NameIdentifier.of( + METALAKE, "renamed_catalog", "renamed_schema", "function")); + assertEquals(function.id(), loaded.id()); + } finally { + SessionUtils.rollbackTransaction(); + } + }); + } + + private void assertFunctionGrantName(String expected, boolean listRoles) throws Exception { + RoleEntity loaded; + if (listRoles) { + List<RoleEntity> roles = + RoleMetaService.getInstance() + .listRolesByMetadataObject( + NameIdentifier.parse(METALAKE + "." + expected), + Entity.EntityType.FUNCTION, + true); + assertEquals(1, roles.size()); + loaded = roles.get(0); + } else { + loaded = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE); + } + assertEquals(1, loaded.securableObjects().size()); + assertEquals(expected, loaded.securableObjects().get(0).fullName()); + assertEquals( + List.of(Privileges.ExecuteFunction.allow()), loaded.securableObjects().get(0).privileges()); + } + + private void withReaderCache(CheckedRunnable action) throws Exception { + CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {}); + cache.put(catalog); + cache.put(schema); + GravitinoEnv env = Mockito.mock(GravitinoEnv.class); + Mockito.when(env.cacheEnabled()).thenReturn(true); + try (MockedStatic<GravitinoEnv> environments = Mockito.mockStatic(GravitinoEnv.class)) { + environments.when(GravitinoEnv::getInstance).thenReturn(env); + EntityIdService.initialize( + new CachedEntityIdResolver(cache, new RelationalEntityStoreIdResolver())); + action.run(); + assertTrue(cache.contains(catalog.nameIdentifier(), Entity.EntityType.CATALOG)); + assertTrue(cache.contains(schema.nameIdentifier(), Entity.EntityType.SCHEMA)); + assertFalse(cache.contains(role.nameIdentifier(), Entity.EntityType.ROLE)); + } finally { + EntityIdService.initialize(new RelationalEntityStoreIdResolver()); + cache.clear(); + } + } + + private <T> T onPeer(Callable<T> action) throws Exception { + ExecutorService peer = Executors.newSingleThreadExecutor(); + try { + return peer.submit( + () -> { + // A peer has its own resolver and SQL session, not the reader's stale cache. + RelationalEntityStoreIdResolver resolver = new RelationalEntityStoreIdResolver(); + try (MockedStatic<EntityIdService> ids = + Mockito.mockStatic(EntityIdService.class)) { + ids.when(() -> EntityIdService.getEntityId(Mockito.any(), Mockito.any())) + .thenAnswer( + invocation -> + resolver.getEntityId( + invocation.getArgument(0), invocation.getArgument(1))); + ids.when(() -> EntityIdService.getEntityIds(Mockito.any(), Mockito.any())) + .thenAnswer( + invocation -> + resolver.getEntityIds( + invocation.getArgument(0), invocation.getArgument(1))); + return action.call(); + } + }) + .get(20, TimeUnit.SECONDS); + } finally { + peer.shutdownNow(); + assertTrue(peer.awaitTermination(10, TimeUnit.SECONDS)); + } + } + + @FunctionalInterface + private interface CheckedRunnable { + /** Runs one scenario that may perform database operations. */ + void run() throws Exception; + } +} diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java index 87bcb656b7..c17a8efa2e 100644 --- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java +++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java @@ -42,15 +42,18 @@ import org.apache.gravitino.meta.FilesetEntity; import org.apache.gravitino.meta.FunctionEntity; import org.apache.gravitino.meta.GroupEntity; import org.apache.gravitino.meta.ModelEntity; +import org.apache.gravitino.meta.PolicyEntity; import org.apache.gravitino.meta.RoleEntity; import org.apache.gravitino.meta.SchemaEntity; import org.apache.gravitino.meta.TableEntity; +import org.apache.gravitino.meta.TagEntity; import org.apache.gravitino.meta.TopicEntity; import org.apache.gravitino.meta.UserEntity; import org.apache.gravitino.meta.ViewEntity; import org.apache.gravitino.storage.RandomIdGenerator; import org.apache.gravitino.storage.relational.TestJDBCBackend; import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.gravitino.utils.NamespaceUtil; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; @@ -65,6 +68,52 @@ class TestOwnerMetaService extends TestJDBCBackend { private static final String FILESET_NAME = "fileset_for_owner_test"; private static final String TOPIC_NAME = "topic_for_owner_test"; + /** Existing dotted tag/policy names support owner lookup and single/batch owner changes. */ + @TestTemplate + void testOwnersForLegacyDottedNames() throws IOException { + createAndInsertMakeLake(METALAKE_NAME); + UserEntity user = + createUserEntity( + RandomIdGenerator.INSTANCE.nextId(), + AuthorizationUtils.ofUserNamespace(METALAKE_NAME), + "legacy_owner", + AUDIT_INFO); + GroupEntity group = + createGroupEntity( + RandomIdGenerator.INSTANCE.nextId(), + AuthorizationUtils.ofGroupNamespace(METALAKE_NAME), + "legacy_group", + AUDIT_INFO); + backend.insert(user, false); + backend.insert(group, false); + TagEntity tag = createAndInsertTagEntity("legacy.tag", "", METALAKE_NAME); + PolicyEntity policy = + createPolicy( + RandomIdGenerator.INSTANCE.nextId(), + NamespaceUtil.ofPolicy(METALAKE_NAME), + "legacy.policy", + AUDIT_INFO); + backend.insert(policy, false); + OwnerMetaService service = OwnerMetaService.getInstance(); + Map<NameIdentifier, Entity.EntityType> objects = + Map.of( + tag.nameIdentifier(), Entity.EntityType.TAG, + policy.nameIdentifier(), Entity.EntityType.POLICY); + for (Map.Entry<NameIdentifier, Entity.EntityType> object : objects.entrySet()) { + service.setOwner(object.getKey(), object.getValue(), user.nameIdentifier(), user.type()); + UserEntity loadedUser = + (UserEntity) service.getOwner(object.getKey(), object.getValue()).orElseThrow(); + Assertions.assertEquals(user.id(), loadedUser.id()); + service.batchSetOwners( + List.of(object.getKey()), object.getValue(), group.nameIdentifier(), group.type()); + GroupEntity loadedGroup = + (GroupEntity) service.getOwner(object.getKey(), object.getValue()).orElseThrow(); + Assertions.assertEquals(group.id(), loadedGroup.id()); + Assertions.assertEquals( + 1, service.batchGetOwner(List.of(object.getKey()), object.getValue()).size()); + } + } + @TestTemplate void testDifferentOwners() throws IOException { BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME); diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPOStorageReadRouting.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPOStorageReadRouting.java index b0e09a0780..2b10de5a04 100644 --- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPOStorageReadRouting.java +++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPOStorageReadRouting.java @@ -23,13 +23,16 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import java.util.Collections; import java.util.List; import org.apache.gravitino.Entity; import org.apache.gravitino.NameIdentifier; import org.apache.gravitino.Namespace; +import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; @@ -37,6 +40,27 @@ public class TestPOStorageReadRouting { private static final Object MAPPER = new Object(); + /** Functions follow the shared parent-ID route when entity caching is enabled. */ + @Test + public void functionsUseParentIdForCachedGetAndList() { + FunctionMetaMapper mapper = mock(FunctionMetaMapper.class); + FunctionPOStorageOps ops = new FunctionPOStorageOps(); + Namespace namespace = Namespace.of("ml", "cat", "schema"); + try (MockedStatic<EntityIdService> entityIds = mockStatic(EntityIdService.class)) { + entityIds + .when( + () -> + EntityIdService.getEntityId( + NameIdentifier.of(namespace.levels()), Entity.EntityType.SCHEMA)) + .thenReturn(42L); + POStorageReadRouting.getPO( + mapper, NameIdentifier.of(namespace, "function"), ops, Entity.EntityType.FUNCTION, true); + POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.FUNCTION, true); + verify(mapper).selectFunctionMetaBySchemaIdAndName(42L, "function"); + verify(mapper).listFunctionPOsBySchemaId(42L); + } + } + @Test public void getPOUsesFullNameWhenCacheDisabled() { RecordingOps ops = new RecordingOps(true); diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java index 3d3f57a069..480cb61de3 100644 --- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java +++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java @@ -560,6 +560,31 @@ class TestRoleMetaService extends TestJDBCBackend { assertEquals(Lists.newArrayList(role1, role2), roleEntities); } + /** Reading roles for existing dotted names does not invoke strict write-name conversion. */ + @TestTemplate + void testListRolesForLegacyDottedNames() throws IOException { + createAndInsertMakeLake(METALAKE_NAME); + TagEntity tag = createAndInsertTagEntity("legacy.tag", "", METALAKE_NAME); + PolicyEntity policy = + createPolicy( + RandomIdGenerator.INSTANCE.nextId(), + NamespaceUtil.ofPolicy(METALAKE_NAME), + "legacy.policy", + AUDIT_INFO); + backend.insert(policy, false); + for (boolean allFields : new boolean[] {false, true}) { + assertTrue( + RoleMetaService.getInstance() + .listRolesByMetadataObject(tag.nameIdentifier(), Entity.EntityType.TAG, allFields) + .isEmpty()); + assertTrue( + RoleMetaService.getInstance() + .listRolesByMetadataObject( + policy.nameIdentifier(), Entity.EntityType.POLICY, allFields) + .isEmpty()); + } + } + @TestTemplate void testDeleteMetalake() throws IOException { BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME); diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java index ed97827aef..fbfdd1fbb1 100644 --- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java +++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java @@ -68,6 +68,193 @@ public class TestTagMetaService extends TestJDBCBackend { private final Map<String, String> props = ImmutableMap.of("k1", "v1"); +<<<<<<< HEAD +======= + /** Legacy dotted object names remain readable by single and batch relation queries. */ + @TestTemplate + public void testReadTagsForLegacyDottedNames() throws IOException { + createAndInsertMakeLake(METALAKE_NAME); + TagEntity tag = createAndInsertTagEntity("legacy.tag", "", METALAKE_NAME); + PolicyEntity policy = + createPolicy( + RandomIdGenerator.INSTANCE.nextId(), + NamespaceUtil.ofPolicy(METALAKE_NAME), + "legacy.policy", + AUDIT_INFO); + backend.insert(policy, false); + TagMetaService service = TagMetaService.getInstance(); + Map<NameIdentifier, Entity.EntityType> objects = + Map.of( + tag.nameIdentifier(), Entity.EntityType.TAG, + policy.nameIdentifier(), Entity.EntityType.POLICY); + for (Map.Entry<NameIdentifier, Entity.EntityType> object : objects.entrySet()) { + assertTrue(service.listTagsForMetadataObject(object.getKey(), object.getValue()).isEmpty()); + assertTrue( + service + .listTagsForMetadataObjects(List.of(object.getKey()), object.getValue()) + .isEmpty()); + Assertions.assertThrows( + NoSuchEntityException.class, + () -> + service.getTagForMetadataObject( + object.getKey(), object.getValue(), tag.nameIdentifier())); + } + } + + /** Verifies a deleted ID is rejected permanently instead of producing a retryable conflict. */ + @TestTemplate + public void testOverwriteRejectsDeletedTagId() throws IOException { + createAndInsertMakeLake(METALAKE_NAME); + TagEntity tag = + TagEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName("deleted_tag_id") + .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)) + .withAuditInfo(AUDIT_INFO) + .build(); + TagMetaService service = TagMetaService.getInstance(); + service.insertTag(tag, false); + assertTrue(service.deleteTag(tag.nameIdentifier())); + EntityAlreadyExistsException failure = + Assertions.assertThrows( + EntityAlreadyExistsException.class, () -> service.insertTag(tag, true)); + assertTrue(failure.getMessage().contains("use a new ID")); + Assertions.assertThrows( + NoSuchEntityException.class, () -> service.getTagByIdentifier(tag.nameIdentifier())); + TagEntity replacement = + TagEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName(tag.name()) + .withNamespace(tag.namespace()) + .withAuditInfo(AUDIT_INFO) + .build(); + service.insertTag(replacement, true); + assertEquals(replacement.id(), service.getTagByIdentifier(tag.nameIdentifier()).id()); + } + + /** Verifies an assignment ignores tags dropped or renamed after they were resolved by name. */ + @TestTemplate + public void testAssignmentLockSkipsTagsDroppedOrRenamedAfterResolution() throws IOException { + createAndInsertMakeLake(METALAKE_NAME); + TagMetaService service = TagMetaService.getInstance(); + List<TagPO> observed = new ArrayList<>(); + for (String name : List.of("kept_tag", "dropped_tag", "renamed_tag")) { + TagEntity tag = + TagEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName(name) + .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)) + .withAuditInfo(AUDIT_INFO) + .build(); + service.insertTag(tag, false); + observed.add( + SessionUtils.getWithoutCommit( + TagMetaMapper.class, mapper -> mapper.selectTagByTagIdForUpdate(tag.id()))); + } + + // Both changes commit after the assignment resolved the names but before it locks the rows. + assertTrue(service.deleteTag(NameIdentifierUtil.ofTag(METALAKE_NAME, "dropped_tag"))); + service.updateTag( + NameIdentifierUtil.ofTag(METALAKE_NAME, "renamed_tag"), + tag -> + TagEntity.builder() + .withId(tag.id()) + .withName("renamed_tag_new") + .withNamespace(tag.namespace()) + .withAuditInfo(AUDIT_INFO) + .build()); + + List<TagPO> locked = + SessionUtils.doWithCommitAndFetchResult( + TagMetaMapper.class, ignored -> TagMetaService.lockTagsForAssignment(observed)); + assertEquals( + List.of("kept_tag"), locked.stream().map(TagPO::getTagName).collect(Collectors.toList())); + } + + /** Verifies first-time overwrites either serialize or report a retryable insert conflict. */ + @TestTemplate + public void testConcurrentOverwriteOfMissingTag() throws Exception { + createAndInsertMakeLake(METALAKE_NAME); + TagEntity first = + TagEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName("tag_first_overwrite") + .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)) + .withAuditInfo(AUDIT_INFO) + .build(); + TagEntity second = + TagEntity.builder() + .withId(RandomIdGenerator.INSTANCE.nextId()) + .withName(first.name()) + .withNamespace(first.namespace()) + .withComment("second overwrite") + .withAuditInfo(AUDIT_INFO) + .build(); + TagMetaService service = TagMetaService.getInstance(); + CountDownLatch firstWritten = new CountDownLatch(1); + CountDownLatch allowCommit = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future<Throwable> firstResult = + executor.submit( + () -> { + SessionUtils.beginTransaction(); + try { + service.insertTag(first, true); + firstWritten.countDown(); + await(allowCommit); + SessionUtils.commitTransaction(); + return null; + } catch (Throwable failure) { + SessionUtils.rollbackTransaction(); + return failure; + } + }); + try { + assertTrue(firstWritten.await(30, TimeUnit.SECONDS)); + Future<Throwable> secondResult = + executor.submit( + () -> { + secondStarted.countDown(); + try { + service.insertTag(second, true); + return null; + } catch (Throwable failure) { + return failure; + } + }); + assertTrue(secondStarted.await(30, TimeUnit.SECONDS)); + Assertions.assertThrows( + TimeoutException.class, () -> secondResult.get(500, TimeUnit.MILLISECONDS)); + allowCommit.countDown(); + Assertions.assertNull(firstResult.get(30, TimeUnit.SECONDS)); + Throwable failure = secondResult.get(30, TimeUnit.SECONDS); + if (failure != null) { + assertTrue( + failure instanceof OptimisticLockException, () -> "Unexpected failure: " + failure); + assertEquals(first.id(), service.getTagByIdentifier(first.nameIdentifier()).id()); + Assertions.assertNull( + SessionUtils.getWithoutCommit( + TagMetaMapper.class, mapper -> mapper.selectTagByTagId(second.id()))); + service.insertTag(second, true); + } + TagEntity stored = service.getTagByIdentifier(first.nameIdentifier()); + assertEquals(first.id(), stored.id()); + assertEquals("second overwrite", stored.comment()); + TagPO storedPO = + SessionUtils.getWithoutCommit( + TagMetaMapper.class, mapper -> mapper.selectTagByTagId(first.id())); + assertEquals(2L, storedPO.getCurrentVersion().longValue()); + Assertions.assertNull( + SessionUtils.getWithoutCommit( + TagMetaMapper.class, mapper -> mapper.selectTagByTagId(second.id()))); + } finally { + allowCommit.countDown(); + executor.shutdownNow(); + } + } + +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) @TestTemplate public void testMetaLifeCycleFromCreationToDeletion() throws IOException { BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME); diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java b/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java index 5bdf6a6312..ed13986229 100644 --- a/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java +++ b/core/src/test/java/org/apache/gravitino/storage/relational/session/TestSqlSession.java @@ -32,6 +32,7 @@ import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; @@ -44,12 +45,15 @@ import java.util.UUID; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.io.FileUtils; import org.apache.gravitino.Config; +import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper; +import org.apache.gravitino.storage.relational.utils.SessionUtils; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.mockito.Mockito; public class TestSqlSession { @@ -145,6 +149,29 @@ public class TestSqlSession { assertEquals(0, SqlSessions.getSessionCount()); } + /** An unsuccessful fresh-read acquisition cannot release the caller's existing session. */ + @Test + public void testFreshReadAcquisitionFailurePreservesOuterSession() { + SqlSession outer = SqlSessions.getSqlSession(); + ThreadLocal<SqlSession> context = SqlSessions.getSessions(); + IllegalStateException failure = new IllegalStateException("session acquisition failed"); + try (MockedStatic<SqlSessions> sessions = Mockito.mockStatic(SqlSessions.class)) { + sessions.when(SqlSessions::getSqlSession).thenThrow(failure); + sessions.when(SqlSessions::closeSqlSession).thenCallRealMethod(); + sessions.when(SqlSessions::getSessionCount).thenCallRealMethod(); + assertSame( + failure, + assertThrows( + IllegalStateException.class, + () -> SessionUtils.getWithoutCommitFresh(CatalogMetaMapper.class, mapper -> null))); + assertSame(outer, context.get()); + assertEquals(1, SqlSessions.getSessionCount()); + sessions.verify(SqlSessions::closeSqlSession, Mockito.never()); + } finally { + SqlSessions.rollbackAndCloseSqlSession(); + } + } + @Test public void testOpenAndCommitAndCloseSqlSession() { SqlSession session = SqlSessions.getSqlSession(); diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java index 3a4312faf8..05f457c90b 100644 --- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java +++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java @@ -94,6 +94,13 @@ import org.apache.gravitino.function.FunctionImpls; import org.apache.gravitino.function.FunctionParam; import org.apache.gravitino.function.FunctionParams; import org.apache.gravitino.function.FunctionType; +<<<<<<< HEAD +======= +import org.apache.gravitino.hook.TagHookDispatcher; +import org.apache.gravitino.json.PolicyAssociationSelectorSerde; +import org.apache.gravitino.listener.EventBus; +import org.apache.gravitino.listener.TagEventDispatcher; +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) import org.apache.gravitino.lock.LockManager; import org.apache.gravitino.meta.AuditInfo; import org.apache.gravitino.meta.BaseMetalake; @@ -718,6 +725,50 @@ public class TestTagManager { Assertions.assertEquals("Metalake non_existent_metalake does not exist", e.getMessage()); } + /** Invalid create/rename requests must never leave a persisted dotted name. */ + @Test + public void testRejectDottedNameBeforeWrite() throws IOException { + TagDispatcher dispatcher = + new TagEventDispatcher(new EventBus(List.of()), new TagHookDispatcher(tagManager)); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> dispatcher.createTag(METALAKE, "invalid.tag", null, Map.of())); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + dispatcher.createTag( + METALAKE, "invalid.tag", null, Map.of(), TagValueConstraint.anyValue())); + Assertions.assertFalse( + entityStore.exists( + NameIdentifierUtil.ofTag(METALAKE, "invalid.tag"), Entity.EntityType.TAG)); + Tag original = tagManager.createTag(METALAKE, "valid_tag", null, Map.of()); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> dispatcher.alterTag(METALAKE, original.name(), TagChange.rename("invalid.tag"))); + Assertions.assertEquals(original, tagManager.getTag(METALAKE, original.name())); + Assertions.assertFalse( + entityStore.exists( + NameIdentifierUtil.ofTag(METALAKE, "invalid.tag"), Entity.EntityType.TAG)); + } + + /** A legacy dotted tag remains readable and removable through the manager. */ + @Test + public void testLegacyDottedTagRecovery() throws IOException { + TagEntity legacy = + TagEntity.builder() + .withId(idGenerator.nextId()) + .withName("legacy.tag") + .withNamespace(NameIdentifierUtil.ofTag(METALAKE, "legacy.tag").namespace()) + .withProperties(Map.of()) + .withAuditInfo( + AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build()) + .build(); + entityStore.put(legacy, false); + Assertions.assertEquals(legacy.name(), tagManager.getTag(METALAKE, legacy.name()).name()); + Assertions.assertTrue(Arrays.asList(tagManager.listTags(METALAKE)).contains(legacy.name())); + Assertions.assertTrue(tagManager.deleteTag(METALAKE, legacy.name())); + } + @Test public void testAlterTag() { String tagComment = "tag comment"; @@ -871,6 +922,20 @@ public class TestTagManager { Assertions.assertEquals("Metalake non_existent_metalake does not exist", e.getMessage()); } + /** Tag/policy objects cannot reach metadata tag-association writes through the manager. */ + @Test + public void testTagAndPolicyAssociationTargetsAreRejected() { + for (MetadataObject.Type type : + new MetadataObject.Type[] {MetadataObject.Type.TAG, MetadataObject.Type.POLICY}) { + MetadataObject object = MetadataObjects.of(null, "legacy.with.dot", type); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + tagManager.associateTagsForMetadataObject( + METALAKE, object, new String[] {"tag"}, new String[0])); + } + } + @Test public void testAssociateTagsForMetadataObject() { Tag tag1 = tagManager.createTag(METALAKE, "tag1", null, null); diff --git a/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java b/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java index 8ff6f37e2b..a87268262a 100644 --- a/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java +++ b/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java @@ -187,6 +187,55 @@ public class TestNameIdentifierUtil { topicException.getMessage()); } + /** Legacy tag/policy names retain their literal name and type for authorization and cleanup. */ + @Test + public void testLegacyDottedTagAndPolicyMetadataObjects() { + for (Entity.EntityType type : + new Entity.EntityType[] {Entity.EntityType.TAG, Entity.EntityType.POLICY}) { + NameIdentifier ident = + type == Entity.EntityType.TAG + ? NameIdentifierUtil.ofTag("metalake1", "legacy.with.dot") + : NameIdentifierUtil.ofPolicy("metalake1", "legacy.with.dot"); + assertThrows( + IllegalNameIdentifierException.class, + () -> NameIdentifierUtil.toMetadataObject(ident, type)); + MetadataObject object = NameIdentifierUtil.toMetadataObjectForRead(ident, type); + assertEquals("legacy.with.dot", object.name()); + assertEquals("legacy.with.dot", object.fullName()); + assertEquals(MetadataObject.Type.valueOf(type.name()), object.type()); + assertEquals(null, object.parent()); + assertEquals(ident, MetadataObjectUtil.toEntityIdent("metalake1", object)); + assertThrows( + IllegalNameIdentifierException.class, + () -> NameIdentifierUtil.checkMetadataObjectName(ident, type)); + } + } + + /** The read conversion retains namespace and external-object name validation. */ + @Test + public void testReadConversionRetainsStrictValidation() { + assertThrows( + IllegalArgumentException.class, + () -> NameIdentifierUtil.toMetadataObjectForRead(null, Entity.EntityType.TAG)); + assertThrows( + IllegalArgumentException.class, + () -> NameIdentifierUtil.toMetadataObjectForRead(NameIdentifier.of("tag"), null)); + for (Entity.EntityType type : + new Entity.EntityType[] {Entity.EntityType.TAG, Entity.EntityType.POLICY}) { + assertThrows( + IllegalNamespaceException.class, + () -> NameIdentifierUtil.toMetadataObjectForRead(NameIdentifier.of("legacy.tag"), type)); + } + NameIdentifier table = NameIdentifier.of("metalake1", "catalog1", "schema1", "sales.2024"); + assertThrows( + IllegalNameIdentifierException.class, + () -> NameIdentifierUtil.toMetadataObjectForRead(table, Entity.EntityType.TABLE)); + NameIdentifier valid = NameIdentifier.of("metalake1", "catalog1", "schema1", "sales"); + assertEquals( + NameIdentifierUtil.toMetadataObject(valid, Entity.EntityType.TABLE), + NameIdentifierUtil.toMetadataObjectForRead(valid, Entity.EntityType.TABLE)); + } + @Test void testOfUser() { String userName = "userA"; diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergHiveCachedClientPool.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergHiveCachedClientPool.java index 9c15639d1d..eb99120ee8 100644 --- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergHiveCachedClientPool.java +++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/utils/IcebergHiveCachedClientPool.java @@ -78,6 +78,11 @@ import org.slf4j.LoggerFactory; * original name is A and when a new user B tries to call the clientPool() method, it will use the * connection that belongs to A. This will not work with kerberos authentication as it will change * the user name. + * + * <p>The shared cache expires each key after the configured idle interval and closes removed pools. + * There is no maximum cache size: expiry limits idle retention, but does not bound the number of + * active identities or pools created within an expiry interval. By default, fresh proxy UGIs and + * renewed delegation tokens for the same authentication identity reuse the same key. */ public class IcebergHiveCachedClientPool implements ClientPool<IMetaStoreClient, TException>, Closeable { @@ -168,6 +173,20 @@ public class IcebergHiveCachedClientPool List<Object> elements = Lists.newArrayList(); elements.add(conf.get(HiveConf.ConfVars.METASTOREURIS.varname, "")); elements.add(conf.get("HIVE_CONF_CATALOG", "hive")); + // The cache is shared across catalogs. Never reuse a connection opened with different + // authentication settings, even when the metastore URI and current subject match. + elements.add(conf.get("hadoop.security.authentication", "simple")); + elements.add(conf.getBoolean(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname, false)); + elements.add(conf.get(HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL.varname, "")); + elements.add(conf.get(HiveConf.ConfVars.METASTORE_TOKEN_SIGNATURE.varname, "")); + try { + // Proxy UGIs are recreated for each request. Share pools by authentication identity, not + // Subject identity, while keeping different real users and auth methods isolated. HMS + // delegation tokens are issued per request and must not prevent reuse by the same identity. + elements.add(authenticationIdentity(UserGroupInformation.getCurrentUser())); + } catch (IOException e) { + throw new UncheckedIOException(e); + } if (cacheKeys == null || cacheKeys.isEmpty()) { return Key.of(elements); } @@ -218,6 +237,13 @@ public class IcebergHiveCachedClientPool return Key.of(elements); } + private static List<Object> authenticationIdentity(UserGroupInformation user) { + return List.of( + user.getUserName(), + user.getAuthenticationMethod(), + user.getRealUser() == null ? List.of() : authenticationIdentity(user.getRealUser())); + } + static class Key { private final List<Object> elements; diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergHiveCachedClientPool.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergHiveCachedClientPool.java index 4a5ef88543..0020700cb8 100644 --- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergHiveCachedClientPool.java +++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergHiveCachedClientPool.java @@ -22,9 +22,15 @@ package org.apache.gravitino.iceberg.common.utils; import com.google.common.collect.Maps; import java.io.IOException; import java.security.PrivilegedAction; +import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.thrift.DelegationTokenIdentifier; +import org.apache.hadoop.io.Text; import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; +import org.apache.hadoop.security.token.Token; +import org.apache.iceberg.CatalogProperties; import org.apache.iceberg.hive.HiveClientPool; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -100,6 +106,105 @@ public class TestIcebergHiveCachedClientPool { Assertions.assertNotEquals(key9, key10); } + @Test + void testClientPoolsIsolateSubjectsEvenWithUsernameCacheKey() throws Exception { + Configuration configuration = new Configuration(false); + configuration.set("hive.metastore.uris", "thrift://identity-test:9083"); + UserGroupInformation login = UserGroupInformation.createRemoteUser("catalog"); + UserGroupInformation proxy = UserGroupInformation.createProxyUser("catalog", login); + try (IcebergHiveCachedClientPool pool = + new IcebergHiveCachedClientPool( + configuration, Map.of(CatalogProperties.CLIENT_POOL_CACHE_KEYS, "USER_NAME"))) { + HiveClientPool loginPool = login.doAs((PrivilegedAction<HiveClientPool>) pool::clientPool); + HiveClientPool proxyPool = proxy.doAs((PrivilegedAction<HiveClientPool>) pool::clientPool); + Assertions.assertNotSame(loginPool, proxyPool); + Assertions.assertSame( + loginPool, login.doAs((PrivilegedAction<HiveClientPool>) pool::clientPool)); + Assertions.assertSame( + proxyPool, proxy.doAs((PrivilegedAction<HiveClientPool>) pool::clientPool)); + } + } + + @Test + void testClientPoolsIsolateDefaultSubjectsAndAuthenticationSettings() throws Exception { + Configuration simple = new Configuration(false); + simple.set("hive.metastore.uris", "thrift://authentication-test:9083"); + Configuration kerberos = new Configuration(simple); + kerberos.setBoolean("hive.metastore.sasl.enabled", true); + kerberos.set("hive.metastore.kerberos.principal", "hive/[email protected]"); + UserGroupInformation first = UserGroupInformation.createRemoteUser("first"); + UserGroupInformation second = UserGroupInformation.createRemoteUser("second"); + try (IcebergHiveCachedClientPool simplePool = + new IcebergHiveCachedClientPool(simple, Map.of()); + IcebergHiveCachedClientPool kerberosPool = + new IcebergHiveCachedClientPool(kerberos, Map.of())) { + HiveClientPool firstPool = + first.doAs((PrivilegedAction<HiveClientPool>) simplePool::clientPool); + Assertions.assertNotSame( + firstPool, second.doAs((PrivilegedAction<HiveClientPool>) simplePool::clientPool)); + Assertions.assertNotSame( + firstPool, first.doAs((PrivilegedAction<HiveClientPool>) kerberosPool::clientPool)); + } + } + + @Test + void testRepeatedProxyRequestsReusePool() throws Exception { + Configuration configuration = new Configuration(false); + configuration.set("hive.metastore.uris", "thrift://proxy-reuse-test:9083"); + UserGroupInformation login = UserGroupInformation.createRemoteUser("service"); + login.setAuthenticationMethod(AuthenticationMethod.KERBEROS); + for (Map<String, String> properties : + List.of( + Map.<String, String>of(), + Map.of(CatalogProperties.CLIENT_POOL_CACHE_KEYS, "USER_NAME"))) { + try (IcebergHiveCachedClientPool pool = + new IcebergHiveCachedClientPool(configuration, properties)) { + HiveClientPool first = + proxyWithToken(login, 0).doAs((PrivilegedAction<HiveClientPool>) pool::clientPool); + for (int request = 1; request <= 10; request++) { + UserGroupInformation proxy = proxyWithToken(login, request); + Assertions.assertSame( + first, proxy.doAs((PrivilegedAction<HiveClientPool>) pool::clientPool)); + } + } + } + } + + @Test + void testRealUsersAndAuthenticationMethodsRemainIsolated() throws Exception { + Configuration configuration = new Configuration(false); + UserGroupInformation first = UserGroupInformation.createRemoteUser("service"); + first.setAuthenticationMethod(AuthenticationMethod.KERBEROS); + UserGroupInformation second = UserGroupInformation.createRemoteUser("other"); + second.setAuthenticationMethod(AuthenticationMethod.KERBEROS); + UserGroupInformation simple = UserGroupInformation.createRemoteUser("service"); + try (IcebergHiveCachedClientPool pool = + new IcebergHiveCachedClientPool(configuration, Map.of())) { + HiveClientPool original = + UserGroupInformation.createProxyUser("alice", first) + .doAs((PrivilegedAction<HiveClientPool>) pool::clientPool); + for (UserGroupInformation real : List.of(second, simple)) { + Assertions.assertNotSame( + original, + UserGroupInformation.createProxyUser("alice", real) + .doAs((PrivilegedAction<HiveClientPool>) pool::clientPool)); + } + } + } + + @Test + void testTokenSignatureSettingsRemainIsolated() throws Exception { + Configuration first = new Configuration(false); + first.set("hive.metastore.token.signature", "first"); + Configuration second = new Configuration(first); + second.set("hive.metastore.token.signature", "second"); + try (IcebergHiveCachedClientPool firstPool = new IcebergHiveCachedClientPool(first, Map.of()); + IcebergHiveCachedClientPool secondPool = + new IcebergHiveCachedClientPool(second, Map.of())) { + Assertions.assertNotSame(firstPool.clientPool(), secondPool.clientPool()); + } + } + @Test void testCloseMultipleInstances() throws IOException { Configuration configuration = new Configuration(); @@ -113,4 +218,18 @@ public class TestIcebergHiveCachedClientPool { pool2.close(); }); } + + private static UserGroupInformation proxyWithToken(UserGroupInformation login, int sequence) { + UserGroupInformation proxy = UserGroupInformation.createProxyUser("alice", login); + DelegationTokenIdentifier identifier = + new DelegationTokenIdentifier(new Text("alice"), new Text("service"), new Text("service")); + identifier.setSequenceNumber(sequence); + proxy.addToken( + new Token<>( + identifier.getBytes(), + new byte[] {(byte) sequence}, + identifier.getKind(), + new Text("metastore"))); + return proxy; + } } diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java index c1982b1271..0bbd5f2707 100644 --- a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java +++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataAuthzHelper.java @@ -358,7 +358,15 @@ public class MetadataAuthzHelper { if (!enableAuthorization() || nameIdentifiers.length == 0) { return entities; } +<<<<<<< HEAD if (isMetadataObject) { +======= + // Preserve legacy tag/policy names for normal authorization and cleanup. These are + // single-level metadata objects; their full names are never split into parent scopes. + if (METADATA_OBJECT_ENTITY_TYPES.contains(entityType) + && entityType != Entity.EntityType.TAG + && entityType != Entity.EntityType.POLICY) { +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) Arrays.stream(nameIdentifiers) .forEach( identifier -> NameIdentifierUtil.checkMetadataObjectName(identifier, entityType)); diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionEvaluator.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionEvaluator.java index 59d5375774..1f0a44d262 100644 --- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionEvaluator.java +++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionEvaluator.java @@ -145,8 +145,20 @@ public class AuthorizationExpressionEvaluator { metadataNames.forEach( (type, entityNameIdent) -> { if (isMetadataType(type)) { +<<<<<<< HEAD MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(entityNameIdent, type); +======= + MetadataObject metadataObject; + try { + metadataObject = NameIdentifierUtil.toMetadataObjectForRead(entityNameIdent, type); + } catch (IllegalNameIdentifierException e) { + throw e; + } catch (IllegalArgumentException e) { + // Only metadata-name parsing failures are client errors, not authorizer failures. + throw new IllegalMetadataObjectException(e, "%s", e.getMessage()); + } +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) ognlContext.put(type.name(), metadataObject); } ognlContext.put(type.name() + "_NAME_IDENT", entityNameIdent); diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java index 39478da0f1..a2940e9c52 100644 --- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java +++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java @@ -675,7 +675,8 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer { @Override public void handleMetadataOwnerChange( String metalake, Long oldOwnerId, NameIdentifier nameIdentifier, Entity.EntityType type) { - MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(nameIdentifier, type); + MetadataObject metadataObject = + NameIdentifierUtil.toMetadataObjectForRead(nameIdentifier, type); // Owner mutations may happen after drop/recreate with the same name. Invalidate the // name->id mapping as well to prevent using a stale metadataId from metadataIdCache. metadataIdCache.invalidate( @@ -690,7 +691,8 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer { @Override public void handleEntityNameIdMappingChange( String metalake, NameIdentifier nameIdentifier, Entity.EntityType type) { - MetadataObject metadataObject = NameIdentifierUtil.toMetadataObject(nameIdentifier, type); + MetadataObject metadataObject = + NameIdentifierUtil.toMetadataObjectForRead(nameIdentifier, type); String cacheKey = JcasbinAuthorizationCacheKeys.metadataIdCacheKey(metalake, metadataObject); if (JcasbinAuthorizationCacheKeys.hasNestedMetadataObjects(metadataObject.type())) { // Prefix invalidation removes the object and all nested objects under the same name path. diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataAuthzHelper.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataAuthzHelper.java index e1ba874a68..610e829e95 100644 --- a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataAuthzHelper.java +++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataAuthzHelper.java @@ -146,6 +146,38 @@ public class TestMetadataAuthzHelper { exception.getMessage()); } + /** Dotted legacy names cannot poison the list or bypass its ordinary authorization. */ + @ParameterizedTest + @EnumSource( + value = Entity.EntityType.class, + names = {"TAG", "POLICY"}) + public void testFilterLegacyDottedTagAndPolicyNames(Entity.EntityType type) { + NameIdentifier[] identifiers = { + type == Entity.EntityType.TAG + ? NameIdentifierUtil.ofTag("testMetalake", "valid") + : NameIdentifierUtil.ofPolicy("testMetalake", "valid"), + type == Entity.EntityType.TAG + ? NameIdentifierUtil.ofTag("testMetalake", "legacy.with.dot") + : NameIdentifierUtil.ofPolicy("testMetalake", "legacy.with.dot") + }; + GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class); + when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(true); + withAuthorizer( + authorizer, + () -> { + Assertions.assertArrayEquals( + identifiers, + MetadataAuthzHelper.filterByExpression( + "testMetalake", "ANY(OWNER, METALAKE)", type, identifiers)); + when(authorizer.isOwner(any(), any(), any(), any())).thenReturn(false); + Assertions.assertEquals( + 0, + MetadataAuthzHelper.filterByExpression( + "testMetalake", "ANY(OWNER, METALAKE)", type, identifiers) + .length); + }); + } + @Test public void testFilterPreservesDottedExternalObjectNameWithoutAuthorization() { Config config = gravitinoEnv.config(); diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java index df168535ee..2c7cc31c92 100644 --- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java +++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java @@ -108,6 +108,12 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +<<<<<<< HEAD +======= +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -1796,6 +1802,196 @@ public class TestJcasbinAuthorizer { } @Test +<<<<<<< HEAD +======= + public void testSemanticModelRenameDropAndNameReuseInvalidateLocalCache() throws Exception { + GravitinoCache<String, Long> cache = getMetadataIdCache(jcasbinAuthorizer); + JcasbinAuthorizationLookups lookups = + new JcasbinAuthorizationLookups(cache, getOwnerRelCache(jcasbinAuthorizer)); + CatalogManager catalogs = mock(CatalogManager.class); + BaseCatalog<?> catalog = mock(BaseCatalog.class); + when(catalog.capability()) + .thenReturn( + new Capability() { + @Override + public CapabilityResult caseSensitiveOnName(Scope scope) { + return CapabilityResult.unsupported("case insensitive"); + } + }); + Mockito.doAnswer( + invocation -> { + ThrowableFunction<BaseCatalog<?>, Object> operation = invocation.getArgument(1); + return operation.apply(catalog); + }) + .when(catalogs) + .doWithCatalog(any(), any()); + when(gravitinoEnv.catalogManager()).thenReturn(catalogs); + NameIdentifier oldIdent = NameIdentifier.of(METALAKE, "catalog", "schema", "SalesModel"); + NameIdentifier newIdent = NameIdentifier.of(oldIdent.namespace(), "RenamedModel"); + MetadataObject oldObject = + MetadataObjects.parse("catalog.SCHEMA.SalesModel", MetadataObject.Type.SEMANTIC_MODEL); + MetadataObject newObject = + MetadataObjects.parse("catalog.ScHeMa.RenamedModel", MetadataObject.Type.SEMANTIC_MODEL); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(oldObject, METALAKE), METALAKE)) + .thenReturn(Optional.of(100L)); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(newObject, METALAKE), METALAKE)) + .thenReturn(Optional.of(200L)); + assertEquals( + Optional.of(100L), + lookups.resolveMetadataId(oldObject, METALAKE, new AuthorizationRequestContext())); + assertEquals( + Optional.of(200L), + lookups.resolveMetadataId(newObject, METALAKE, new AuthorizationRequestContext())); + SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class); + SemanticModel renamed = mock(SemanticModel.class); + when(renamed.name()).thenReturn(newIdent.name()); + SemanticModelChange rename = SemanticModelChange.rename(newIdent.name()); + when(dispatcher.alterSemanticModel(oldIdent, SemanticModelSourceUpdate.preserve(), rename)) + .thenReturn(renamed); + when(dispatcher.dropSemanticModel(newIdent)).thenReturn(true); + when(gravitinoEnv.gravitinoAuthorizer()).thenReturn(jcasbinAuthorizer); + SemanticModelHookDispatcher hook = new SemanticModelHookDispatcher(dispatcher, () -> null); + try { + hook.alterSemanticModel(oldIdent, SemanticModelSourceUpdate.preserve(), rename); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(oldObject, METALAKE), METALAKE)) + .thenReturn(Optional.empty()); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(newObject, METALAKE), METALAKE)) + .thenReturn(Optional.of(100L)); + assertEquals( + Optional.empty(), + lookups.resolveMetadataId(oldObject, METALAKE, new AuthorizationRequestContext())); + assertEquals( + Optional.of(100L), + lookups.resolveMetadataId(newObject, METALAKE, new AuthorizationRequestContext())); + hook.dropSemanticModel(newIdent); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(newObject, METALAKE), METALAKE)) + .thenReturn(Optional.of(300L)); + assertEquals( + Optional.of(300L), + lookups.resolveMetadataId(newObject, METALAKE, new AuthorizationRequestContext())); + metadataIdConverterMockedStatic + .when( + () -> + MetadataIdConverter.getID( + MetadataIdConverter.normalizeMetadataObject(oldObject, METALAKE), METALAKE)) + .thenReturn(Optional.of(400L)); + assertEquals( + Optional.of(400L), + lookups.resolveMetadataId(oldObject, METALAKE, new AuthorizationRequestContext())); + } finally { + when(gravitinoEnv.gravitinoAuthorizer()).thenReturn(null); + when(gravitinoEnv.catalogManager()).thenReturn(null); + } + } + + @Test + public void testSemanticModelCacheKeepsCaseSensitiveSchemasDistinct() throws Exception { + CatalogManager catalogs = mock(CatalogManager.class); + BaseCatalog<?> catalog = mock(BaseCatalog.class); + when(catalog.capability()).thenReturn(Capability.DEFAULT); + Mockito.doAnswer( + invocation -> { + ThrowableFunction<BaseCatalog<?>, Object> operation = invocation.getArgument(1); + return operation.apply(catalog); + }) + .when(catalogs) + .doWithCatalog(any(), any()); + when(gravitinoEnv.catalogManager()).thenReturn(catalogs); + JcasbinAuthorizationLookups lookups = + new JcasbinAuthorizationLookups( + getMetadataIdCache(jcasbinAuthorizer), getOwnerRelCache(jcasbinAuthorizer)); + MetadataObject lower = + MetadataObjects.parse("catalog.schema.SalesModel", MetadataObject.Type.SEMANTIC_MODEL); + MetadataObject upper = + MetadataObjects.parse("catalog.SCHEMA.SalesModel", MetadataObject.Type.SEMANTIC_MODEL); + metadataIdConverterMockedStatic + .when(() -> MetadataIdConverter.getID(lower, METALAKE)) + .thenReturn(Optional.of(100L)); + metadataIdConverterMockedStatic + .when(() -> MetadataIdConverter.getID(upper, METALAKE)) + .thenReturn(Optional.of(200L)); + try { + assertEquals( + Optional.of(100L), + lookups.resolveMetadataId(lower, METALAKE, new AuthorizationRequestContext())); + assertEquals( + Optional.of(200L), + lookups.resolveMetadataId(upper, METALAKE, new AuthorizationRequestContext())); + jcasbinAuthorizer.handleEntityNameIdMappingChange( + METALAKE, + NameIdentifier.of(METALAKE, "catalog", "SCHEMA", "SalesModel"), + Entity.EntityType.SEMANTIC_MODEL); + metadataIdConverterMockedStatic + .when(() -> MetadataIdConverter.getID(upper, METALAKE)) + .thenReturn(Optional.of(300L)); + assertEquals( + Optional.of(300L), + lookups.resolveMetadataId(upper, METALAKE, new AuthorizationRequestContext())); + assertEquals( + Optional.of(100L), + lookups.resolveMetadataId(lower, METALAKE, new AuthorizationRequestContext())); + } finally { + when(gravitinoEnv.catalogManager()).thenReturn(null); + } + } + + /** + * Legacy names remain usable when invalidating their authorization mappings and owner cache. + * + * @param type the single-level metadata type + * @throws Exception if the test cache cannot be inspected + */ + @ParameterizedTest + @EnumSource( + value = Entity.EntityType.class, + names = {"TAG", "POLICY"}) + public void testLegacyNameCacheInvalidation(Entity.EntityType type) throws Exception { + NameIdentifier identifier = + type == Entity.EntityType.TAG + ? NameIdentifierUtil.ofTag(METALAKE, "legacy.with.dot") + : NameIdentifierUtil.ofPolicy(METALAKE, "legacy.with.dot"); + MetadataObject object = + MetadataObjects.of(null, "legacy.with.dot", MetadataObject.Type.valueOf(type.name())); + GravitinoCache<String, Long> metadataIds = getMetadataIdCache(jcasbinAuthorizer); + GravitinoCache<Long, Optional<OwnerInfo>> owners = getOwnerRelCache(jcasbinAuthorizer); + String key = JcasbinAuthorizationCacheKeys.metadataIdCacheKey(METALAKE, object); + metadataIdConverterMockedStatic + .when(() -> MetadataIdConverter.getID(object, METALAKE)) + .thenReturn(Optional.of(CATALOG_ID)); + + metadataIds.put(key, CATALOG_ID); + jcasbinAuthorizer.handleEntityNameIdMappingChange(METALAKE, identifier, type); + assertFalse(metadataIds.getIfPresent(key).isPresent()); + + metadataIds.put(key, CATALOG_ID); + owners.put(CATALOG_ID, Optional.of(new OwnerInfo(USER_ID, "USER"))); + jcasbinAuthorizer.handleMetadataOwnerChange(METALAKE, USER_ID, identifier, type); + assertFalse(metadataIds.getIfPresent(key).isPresent()); + assertFalse(owners.getIfPresent(CATALOG_ID).isPresent()); + } + + @Test +>>>>>>> 6b73de4f9 ([#14823] fix: Correct catalog authentication and metadata authorization (#14827)) public void testOwnerCacheInvalidation() throws Exception { // Get the ownerRel cache via reflection GravitinoCache<Long, Optional<OwnerInfo>> ownerRel = getOwnerRelCache(jcasbinAuthorizer);
