This is an automated email from the ASF dual-hosted git repository.

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 6b73de4f9b [#14823] fix: Correct catalog authentication and metadata 
authorization (#14827)
6b73de4f9b is described below

commit 6b73de4f9bafabbacbb95a29d144db9535bd5fe5
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.
---
 .../ranger/RangerClientExtension.java              |  24 ++
 .../ranger/TestRangerClientExtension.java          |  36 ++-
 .../authorization/AuthorizationUtils.java          |   4 +-
 .../org/apache/gravitino/policy/PolicyManager.java |   4 +
 .../relational/service/OwnerMetaService.java       |   6 +-
 .../relational/service/RoleMetaService.java        |  32 +--
 .../storage/relational/service/TagMetaService.java |  10 +-
 .../storage/relational/utils/SessionUtils.java     |  27 +++
 .../java/org/apache/gravitino/tag/TagManager.java  |   4 +
 .../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     |  31 +++
 .../storage/relational/session/TestSqlSession.java |  27 +++
 .../org/apache/gravitino/tag/TestTagManager.java   |  61 +++++
 .../gravitino/utils/TestNameIdentifierUtil.java    |  49 ++++
 .../common/utils/IcebergHiveCachedClientPool.java  |  26 +++
 .../utils/TestIcebergHiveCachedClientPool.java     | 119 ++++++++++
 .../server/authorization/MetadataAuthzHelper.java  |   6 +-
 .../AuthorizationExpressionEvaluator.java          |   2 +-
 .../authorization/jcasbin/JcasbinAuthorizer.java   |   6 +-
 .../authorization/TestMetadataAuthzHelper.java     |  32 +++
 .../jcasbin/TestJcasbinAuthorizer.java             |  36 +++
 26 files changed, 948 insertions(+), 26 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 1bf888d74e..69f450ddd2 100644
--- 
a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
+++ 
b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
@@ -366,7 +366,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);
 
@@ -427,7 +427,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 9932b32756..466d40b749 100644
--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
@@ -172,6 +172,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);
     content.validate();
@@ -388,6 +390,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 4221254694..9140e95438 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
@@ -187,7 +187,7 @@ public class OwnerMetaService {
         POConverters.initializeOwnerRelPOsWithVersion(
             metalakeId, ownerType.name(), ownerId, entityType.name(), 
entityId);
     String metadataObjectType =
-        NameIdentifierUtil.toMetadataObject(entity, entityType).type().name();
+        NameIdentifierUtil.toMetadataObjectForRead(entity, 
entityType).type().name();
     assignOwner(
         metalake,
         metalakeId,
@@ -237,7 +237,9 @@ public class OwnerMetaService {
     }
     entityIds.sort(Comparator.naturalOrder());
     String metadataObjectType =
-        NameIdentifierUtil.toMetadataObject(ownedObjects.get(0), 
ownedObjectType).type().name();
+        NameIdentifierUtil.toMetadataObjectForRead(ownedObjects.get(0), 
ownedObjectType)
+            .type()
+            .name();
 
     List<OwnerRelForDeletion> deletions = new ArrayList<>(entityIds.size());
     List<OwnerRelPO> ownerRelPOs = new ArrayList<>(entityIds.size());
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 d6b4528d7b..d6e7462e17 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
@@ -127,16 +127,19 @@ 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 =
-        SessionUtils.getWithoutCommit(
-            RoleMetaMapper.class,
-            mapper ->
-                allFields
-                    ? mapper.listRolesWithPrivilegesByMetadataObjectIdAndType(
-                        metadataObjectId, metadataObject.type().name())
-                    : mapper.listRolesByMetadataObjectIdAndType(
+        allFields
+            ? SessionUtils.getWithoutCommitFresh(
+                RoleMetaMapper.class,
+                mapper ->
+                    mapper.listRolesWithPrivilegesByMetadataObjectIdAndType(
+                        metadataObjectId, metadataObject.type().name()))
+            : SessionUtils.getWithoutCommit(
+                RoleMetaMapper.class,
+                mapper ->
+                    mapper.listRolesByMetadataObjectIdAndType(
                         metadataObjectId, metadataObject.type().name()));
     return rolePOs.stream()
         .map(
@@ -549,12 +552,13 @@ public class RoleMetaService {
   private static RolePO getRolePOByMetalakeIdAndName(
       Long metalakeId, String roleName, boolean withPrivileges) {
     RolePO rolePO =
-        SessionUtils.getWithoutCommit(
-            RoleMetaMapper.class,
-            mapper ->
-                withPrivileges
-                    ? 
mapper.selectRoleWithPrivilegesByMetalakeIdAndName(metalakeId, roleName)
-                    : mapper.selectRoleMetaByMetalakeIdAndName(metalakeId, 
roleName));
+        withPrivileges
+            ? SessionUtils.getWithoutCommitFresh(
+                RoleMetaMapper.class,
+                mapper -> 
mapper.selectRoleWithPrivilegesByMetalakeIdAndName(metalakeId, roleName))
+            : SessionUtils.getWithoutCommit(
+                RoleMetaMapper.class,
+                mapper -> mapper.selectRoleMetaByMetalakeIdAndName(metalakeId, 
roleName));
 
     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 62effef3bc..3e02b3df50 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
@@ -188,7 +188,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;
@@ -249,7 +250,9 @@ public class TagMetaService {
         });
     List<TagRelationTagPO> rows = new ArrayList<>();
     String metadataObjectType =
-        NameIdentifierUtil.toMetadataObject(objectIdentifiers.get(0), 
objectType).type().toString();
+        NameIdentifierUtil.toMetadataObjectForRead(objectIdentifiers.get(0), 
objectType)
+            .type()
+            .toString();
     for (List<Long> batch : Lists.partition(new 
ArrayList<>(identifiersById.keySet()), 500)) {
       rows.addAll(
           SessionUtils.getWithoutCommit(
@@ -283,7 +286,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);
 
     List<TagPO> tagPOs = 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 54539355bb..0cbb866f36 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 537e10517e..f22c856372 100644
--- a/core/src/main/java/org/apache/gravitino/tag/TagManager.java
+++ b/core/src/main/java/org/apache/gravitino/tag/TagManager.java
@@ -125,6 +125,8 @@ public class TagManager implements TagDispatcher {
       Map<String, String> properties,
       TagValueConstraint valueConstraint)
       throws TagAlreadyExistsException {
+    NameIdentifierUtil.checkMetadataObjectName(
+        NameIdentifierUtil.ofTag(metalake, name), Entity.EntityType.TAG);
     Map<String, String> tagProperties = properties == null ? 
Collections.emptyMap() : properties;
     checkMetalake(NameIdentifier.of(metalake), entityStore);
     TagEntity tagEntity =
@@ -579,6 +581,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 8efb9aab7b..a8dd00bd95 100644
--- a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
@@ -641,6 +641,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}
@@ -735,6 +738,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 9fd2e12d8a..05a175727f 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -98,6 +98,9 @@ import org.apache.gravitino.exceptions.NotFoundException;
 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.lock.LockType;
 import org.apache.gravitino.meta.AuditInfo;
@@ -487,6 +490,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 675797c4bb..97adae2d0c 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
@@ -41,15 +41,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.TestTemplate;
@@ -63,6 +66,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 a203c371e4..eda9424ac2 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
@@ -932,6 +932,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 86910b9c7a..488b7029cd 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
@@ -101,6 +101,37 @@ public class TestTagMetaService extends TestJDBCBackend {
 
   private final Map<String, String> props = ImmutableMap.of("k1", "v1");
 
+  /** 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 {
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 15e824de5a..1c64cd2ab8 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
@@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 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 static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -47,12 +48,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 {
@@ -214,6 +218,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 ee2bc9e42e..94790a2f64 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -110,7 +110,10 @@ import org.apache.gravitino.function.FunctionImpls;
 import org.apache.gravitino.function.FunctionParam;
 import org.apache.gravitino.function.FunctionParams;
 import org.apache.gravitino.function.FunctionType;
+import org.apache.gravitino.hook.TagHookDispatcher;
 import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.TagEventDispatcher;
 import org.apache.gravitino.lock.LockManager;
 import org.apache.gravitino.lock.LockType;
 import org.apache.gravitino.meta.AuditInfo;
@@ -860,6 +863,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";
@@ -1013,6 +1060,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 4a68158c75..78ce09e685 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java
@@ -197,6 +197,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 cefbdffaca..982cbb73cc 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 {
@@ -169,6 +174,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);
     }
@@ -219,6 +238,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 3fd021ba75..3798da7492 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
@@ -417,7 +417,11 @@ public class MetadataAuthzHelper {
     if (!enableAuthorization() || nameIdentifiers.length == 0) {
       return entities;
     }
-    if (METADATA_OBJECT_ENTITY_TYPES.contains(entityType)) {
+    // 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) {
       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 5fcc56bd3e..7c129d1a84 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
@@ -187,7 +187,7 @@ public class AuthorizationExpressionEvaluator {
           if (isMetadataType(type)) {
             MetadataObject metadataObject;
             try {
-              metadataObject = 
NameIdentifierUtil.toMetadataObject(entityNameIdent, type);
+              metadataObject = 
NameIdentifierUtil.toMetadataObjectForRead(entityNameIdent, type);
             } catch (IllegalNameIdentifierException e) {
               throw e;
             } catch (IllegalArgumentException e) {
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 0b8e8eae34..ecb81cca83 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
@@ -826,7 +826,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(
@@ -841,7 +842,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 e04d6577ca..82480170c4 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
@@ -149,6 +149,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 b32c1eb9ce..0912f4b577 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
@@ -144,6 +144,7 @@ import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
 import org.junit.jupiter.params.provider.ValueSource;
 import org.mockito.MockedStatic;
 import org.mockito.Mockito;
@@ -4223,6 +4224,41 @@ public class TestJcasbinAuthorizer {
     }
   }
 
+  /**
+   * 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
   public void testOwnerCacheInvalidation() throws Exception {
     // Get the ownerRel cache via reflection

Reply via email to