World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12176] feat(server, client): expose policy-on-tag APIs (#12964)
roryqif52c6c4745a8
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.javaindex b6d85d5d93..7788a1d44c 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java@@ -1111,6 +1111,10 @@ public class ErrorHandlers {.getType().equals(TagAlreadyAssociatedException.class.getSimpleName())) {throw new TagAlreadyAssociatedException(errorMessage);+ } else if (errorResponse+ .getType()+ .equals(PolicyAlreadyAssociatedException.class.getSimpleName())) {+ throw new PolicyAlreadyAssociatedException(errorMessage);} else {throw new AlreadyExistsException(errorMessage);}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicyTagAssociation.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicyTagAssociation.javanew file mode 100644index 0000000000..36e4d83e87--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericPolicyTagAssociation.java@@ -0,0 +1,53 @@+/*+ * 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.client;++import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyAssociationSelector;+import org.apache.gravitino.policy.PolicyTagAssociation;+import org.apache.gravitino.tag.Tag;++/** Generic client representation of a policy-to-tag association. */+final class GenericPolicyTagAssociation implements PolicyTagAssociation {++ private final Policy policy;+ private final Tag tag;+ private final PolicyAssociationSelector selector;++ GenericPolicyTagAssociation(Policy policy, Tag tag, PolicyAssociationSelector selector) {+ this.policy = policy;+ this.tag = tag;+ this.selector = selector;+ }++ @Override+ public Policy policy() {+ return policy;+ }++ @Override+ public Tag tag() {+ return tag;+ }++ @Override+ public PolicyAssociationSelector selector() {+ return selector;+ }+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.javaindex 3366e63a1d..1ac10b77d0 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClient.java@@ -65,9 +65,11 @@ import org.apache.gravitino.job.JobTemplate;import org.apache.gravitino.job.JobTemplateChange;import org.apache.gravitino.job.SupportsJobs;import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyAssociationSelector;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyOperations;+import org.apache.gravitino.policy.PolicyTagAssociation;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.tag.Tag;@@ -640,6 +642,22 @@ public class GravitinoClient extends GravitinoClientBasereturn getMetalake().deleteTag(name);}+ @Override+ public PolicyTagAssociation[] listPolicyAssociationsForTag(String tagName) {+ return getMetalake().listPolicyAssociationsForTag(tagName);+ }++ @Override+ public PolicyTagAssociation addPolicyForTag(+ String tagName, String policyName, PolicyAssociationSelector selector) {+ return getMetalake().addPolicyForTag(tagName, policyName, selector);+ }++ @Override+ public void removePolicyFromTag(String tagName, String policyName) {+ getMetalake().removePolicyFromTag(tagName, policyName);+ }+@Overridepublic List<JobTemplate> listJobTemplates() {return getMetalake().listJobTemplates();@@ -736,6 +754,11 @@ public class GravitinoClient extends GravitinoClientBasereturn getMetalake().deletePolicy(name);}+ @Override+ public PolicyTagAssociation[] listTagAssociationsForPolicy(String policyName) {+ return getMetalake().listTagAssociationsForPolicy(policyName);+ }+/** Builder class for constructing a GravitinoClient. */public static class ClientBuilder extends GravitinoClientBase.Builder<GravitinoClient> {diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.javaindex dfb2069025..96072b7d8d 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java@@ -49,6 +49,7 @@ import org.apache.gravitino.authorization.User;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.dto.MetalakeDTO;import org.apache.gravitino.dto.authorization.SecurableObjectDTO;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;import org.apache.gravitino.dto.requests.CatalogCreateRequest;import org.apache.gravitino.dto.requests.CatalogSetRequest;import org.apache.gravitino.dto.requests.CatalogUpdateRequest;@@ -61,6 +62,7 @@ import org.apache.gravitino.dto.requests.JobTemplateUpdatesRequest;import org.apache.gravitino.dto.requests.OwnerSetRequest;import org.apache.gravitino.dto.requests.PolicyCreateRequest;import org.apache.gravitino.dto.requests.PolicySetRequest;+import org.apache.gravitino.dto.requests.PolicyTagAddRequest;import org.apache.gravitino.dto.requests.PolicyUpdateRequest;import org.apache.gravitino.dto.requests.PolicyUpdatesRequest;import org.apache.gravitino.dto.requests.PrivilegeGrantRequest;@@ -86,11 +88,14 @@ import org.apache.gravitino.dto.responses.JobTemplateListResponse;import org.apache.gravitino.dto.responses.JobTemplateResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.OwnerResponse;+import org.apache.gravitino.dto.responses.PolicyForTagAssociationListResponse;import org.apache.gravitino.dto.responses.PolicyListResponse;import org.apache.gravitino.dto.responses.PolicyResponse;+import org.apache.gravitino.dto.responses.PolicyTagAssociationResponse;import org.apache.gravitino.dto.responses.RemoveResponse;import org.apache.gravitino.dto.responses.RoleResponse;import org.apache.gravitino.dto.responses.SetResponse;+import org.apache.gravitino.dto.responses.TagForPolicyAssociationListResponse;import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;import org.apache.gravitino.dto.responses.UserListResponse;@@ -126,9 +131,11 @@ import org.apache.gravitino.job.JobTemplate;import org.apache.gravitino.job.JobTemplateChange;import org.apache.gravitino.job.SupportsJobs;import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyAssociationSelector;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyOperations;+import org.apache.gravitino.policy.PolicyTagAssociation;import org.apache.gravitino.rest.RESTUtils;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;@@ -746,6 +753,65 @@ public class GravitinoMetalake extends MetalakeDTOreturn resp.dropped();}+ @Override+ public PolicyTagAssociation[] listPolicyAssociationsForTag(String tagName) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(tagName), "tag name must not be null or empty");+ PolicyForTagAssociationListResponse response =+ restClient.get(+ policyTagPath(tagName),+ ImmutableMap.of("details", "true"),+ PolicyForTagAssociationListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tagErrorHandler());+ response.validate();+ Tag tag = getTag(tagName);+ return Arrays.stream(response.getAssociations())+ .map(+ association ->+ new GenericPolicyTagAssociation(+ new GenericPolicy(association.getPolicy(), restClient, this.name()),+ tag,+ association.getSelector().toSelector()))+ .toArray(PolicyTagAssociation[]::new);+ }++ @Override+ public PolicyTagAssociation addPolicyForTag(+ String tagName, String policyName, PolicyAssociationSelector selector) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(tagName), "tag name must not be null or empty");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(policyName), "policy name must not be null or empty");+ PolicyTagAddRequest request =+ new PolicyTagAddRequest(PolicyAssociationSelectorDTO.fromSelector(selector));+ PolicyTagAssociationResponse response =+ restClient.post(+ policyTagPath(tagName) + "/" + RESTUtils.encodeString(policyName),+ request,+ PolicyTagAssociationResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tagErrorHandler());+ response.validate();+ return new GenericPolicyTagAssociation(+ getPolicy(response.getPolicy()),+ getTag(response.getTag()),+ response.getSelector().toSelector());+ }++ @Override+ public void removePolicyFromTag(String tagName, String policyName) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(tagName), "tag name must not be null or empty");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(policyName), "policy name must not be null or empty");+ restClient.delete(+ policyTagPath(tagName) + "/" + RESTUtils.encodeString(policyName),+ BaseResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tagErrorHandler());+ }+/*** List all the policies under the current metalake.*@@ -924,6 +990,43 @@ public class GravitinoMetalake extends MetalakeDTOreturn resp.dropped();}+ @Override+ public PolicyTagAssociation[] listTagAssociationsForPolicy(String policyName) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(policyName), "policy name must not be null or empty");+ TagForPolicyAssociationListResponse response =+ restClient.get(+ tagPolicyPath(policyName),+ ImmutableMap.of("details", "true"),+ TagForPolicyAssociationListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.policyErrorHandler());+ response.validate();+ Policy policy = getPolicy(policyName);+ return Arrays.stream(response.getAssociations())+ .map(+ association ->+ new GenericPolicyTagAssociation(+ policy,+ new GenericTag(association.getTag(), restClient, this.name()),+ association.getSelector().toSelector()))+ .toArray(PolicyTagAssociation[]::new);+ }++ private String policyTagPath(String tagName) {+ return String.format(API_METALAKES_TAGS_PATH, RESTUtils.encodeString(this.name()))+ + "/"+ + RESTUtils.encodeString(tagName)+ + "/policies";+ }++ private String tagPolicyPath(String policyName) {+ return String.format(API_METALAKES_POLICIES_PATH, RESTUtils.encodeString(this.name()))+ + "/"+ + RESTUtils.encodeString(policyName)+ + "/tags";+ }+/*** Adds a new User.*diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.javaindex 59e413684c..5e69af752c 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoMetalake.java@@ -37,18 +37,22 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.dto.CatalogDTO;import org.apache.gravitino.dto.MetalakeDTO;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;import org.apache.gravitino.dto.policy.PolicyContentDTO;import org.apache.gravitino.dto.policy.PolicyDTO;+import org.apache.gravitino.dto.policy.PolicyForTagAssociationDTO;import org.apache.gravitino.dto.requests.CatalogCreateRequest;import org.apache.gravitino.dto.requests.CatalogUpdateRequest;import org.apache.gravitino.dto.requests.CatalogUpdatesRequest;import org.apache.gravitino.dto.requests.MetalakeCreateRequest;import org.apache.gravitino.dto.requests.PolicyCreateRequest;+import org.apache.gravitino.dto.requests.PolicyTagAddRequest;import org.apache.gravitino.dto.requests.PolicyUpdateRequest;import org.apache.gravitino.dto.requests.PolicyUpdatesRequest;import org.apache.gravitino.dto.requests.TagCreateRequest;import org.apache.gravitino.dto.requests.TagUpdateRequest;import org.apache.gravitino.dto.requests.TagUpdatesRequest;+import org.apache.gravitino.dto.responses.BaseResponse;import org.apache.gravitino.dto.responses.CatalogListResponse;import org.apache.gravitino.dto.responses.CatalogResponse;import org.apache.gravitino.dto.responses.DropResponse;@@ -56,22 +60,30 @@ import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.MetalakeResponse;import org.apache.gravitino.dto.responses.NameListResponse;+import org.apache.gravitino.dto.responses.PolicyForTagAssociationListResponse;import org.apache.gravitino.dto.responses.PolicyListResponse;import org.apache.gravitino.dto.responses.PolicyResponse;+import org.apache.gravitino.dto.responses.PolicyTagAssociationResponse;+import org.apache.gravitino.dto.responses.TagForPolicyAssociationListResponse;import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;import org.apache.gravitino.dto.tag.TagDTO;+import org.apache.gravitino.dto.tag.TagForPolicyAssociationDTO;import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.NoSuchTagException;+import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.exceptions.TagAlreadyExistsException;+import org.apache.gravitino.policy.AllValuesSelector;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.policy.PolicyTagAssociation;+import org.apache.gravitino.policy.TagValueSelector;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagChange;import org.apache.gravitino.tag.TagValueConstraint;@@ -757,6 +769,104 @@ public class TestGravitinoMetalake extends TestBase {Assertions.assertTrue(ex1.getMessage().contains("mock error"));}+ @Test+ public void testPolicyTagAssociations() throws JsonProcessingException {+ String tagName = "tag1";+ String policyName = "policy1";+ String tagPath = "/api/metalakes/" + metalakeName + "/tags/" + tagName;+ String policyPath = "/api/metalakes/" + metalakeName + "/policies/" + policyName;+ String tagPolicyPath = tagPath + "/policies";+ String policyTagPath = policyPath + "/tags";+ Map<String, String> details = Collections.singletonMap("details", "true");++ TagDTO tag =+ TagDTO.builder()+ .withName(tagName)+ .withAudit(+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ PolicyDTO policy =+ PolicyDTO.builder()+ .withName(policyName)+ .withPolicyType("custom")+ .withContent(+ PolicyContentDTO.CustomContentDTO.builder()+ .withSupportedObjectTypes(ImmutableSet.of(MetadataObject.Type.TABLE))+ .build())+ .withAudit(+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ PolicyAssociationSelectorDTO selector =+ PolicyAssociationSelectorDTO.fromSelector(TagValueSelector.of("finance"));++ buildMockResource(+ Method.GET,+ tagPolicyPath,+ details,+ null,+ new PolicyForTagAssociationListResponse(+ new PolicyForTagAssociationDTO[] {new PolicyForTagAssociationDTO(policy, selector)}),+ HttpStatus.SC_OK);+ buildMockResource(Method.GET, tagPath, null, new TagResponse(tag), HttpStatus.SC_OK);++ PolicyTagAssociation[] policies = gravitinoClient.listPolicyAssociationsForTag(tagName);+ Assertions.assertEquals(1, policies.length);+ Assertions.assertEquals(policyName, policies[0].policy().name());+ Assertions.assertEquals(tagName, policies[0].tag().name());+ Assertions.assertEquals(TagValueSelector.of("finance"), policies[0].selector());++ buildMockResource(+ Method.GET,+ policyTagPath,+ details,+ null,+ new TagForPolicyAssociationListResponse(+ new TagForPolicyAssociationDTO[] {new TagForPolicyAssociationDTO(tag, selector)}),+ HttpStatus.SC_OK);+ buildMockResource(Method.GET, policyPath, null, new PolicyResponse(policy), HttpStatus.SC_OK);++ PolicyTagAssociation[] tags = gravitinoClient.listTagAssociationsForPolicy(policyName);+ Assertions.assertEquals(1, tags.length);+ Assertions.assertEquals(policyName, tags[0].policy().name());+ Assertions.assertEquals(tagName, tags[0].tag().name());+ Assertions.assertEquals(TagValueSelector.of("finance"), tags[0].selector());++ PolicyAssociationSelectorDTO allValues =+ PolicyAssociationSelectorDTO.fromSelector(AllValuesSelector.get());+ buildMockResource(+ Method.POST,+ tagPolicyPath + "/" + policyName,+ new PolicyTagAddRequest(allValues),+ new PolicyTagAssociationResponse(policyName, tagName, allValues),+ HttpStatus.SC_OK);+ buildMockResource(Method.GET, policyPath, null, new PolicyResponse(policy), HttpStatus.SC_OK);+ buildMockResource(Method.GET, tagPath, null, new TagResponse(tag), HttpStatus.SC_OK);++ PolicyTagAssociation added = gravitinoClient.addPolicyForTag(tagName, policyName);+ Assertions.assertEquals(AllValuesSelector.get(), added.selector());++ ErrorResponse alreadyAssociated =+ ErrorResponse.alreadyExists(+ PolicyAlreadyAssociatedException.class.getSimpleName(), "mock error");+ buildMockResource(+ Method.POST,+ tagPolicyPath + "/" + policyName,+ new PolicyTagAddRequest(allValues),+ alreadyAssociated,+ HttpStatus.SC_CONFLICT);+ Assertions.assertThrows(+ PolicyAlreadyAssociatedException.class,+ () -> gravitinoClient.addPolicyForTag(tagName, policyName));++ buildMockResource(+ Method.DELETE,+ tagPolicyPath + "/" + policyName,+ null,+ new BaseResponse(),+ HttpStatus.SC_OK);+ Assertions.assertDoesNotThrow(() -> gravitinoClient.removePolicyFromTag(tagName, policyName));+ }+@Testpublic void testListPolicies() throws JsonProcessingException {String path = "/api/metalakes/" + metalakeName + "/policies";diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.javaindex 403bd05c2a..815e49f0d3 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java@@ -564,12 +564,10 @@ public class PolicyIT extends BaseIT {Assertions.assertFalse(policies7[0].inherited().get());Assertions.assertTrue(policies7[0].enabled());- // Test disable the policy then list again+ // Test disabled policies are excluded when listing associated policiesAssertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();- Assertions.assertEquals(1, policies8.length);- Assertions.assertEquals(policy1.name(), policies8[0].name());- Assertions.assertFalse(policies8[0].enabled());+ Assertions.assertEquals(0, policies8.length);Assertions.assertDoesNotThrow(() -> metalake.enablePolicy(policy1.name()));// Test get associated policy for catalogdiff --git a/clients/client-python/gravitino/api/authorization/privileges.py b/clients/client-python/gravitino/api/authorization/privileges.pyindex edeeb15d54..41402b9e63 100644--- a/clients/client-python/gravitino/api/authorization/privileges.py+++ b/clients/client-python/gravitino/api/authorization/privileges.py@@ -162,12 +162,18 @@ class Privilege(ABC):APPLY_TAG = (0, 1 << 22)"""The privilege to apply a tag."""+ VIEW_TAG = (0, 1 << 34)+ """The privilege to view tag metadata and associations."""+CREATE_POLICY = (0, 1 << 23)"""The privilege to create a policy."""APPLY_POLICY = (0, 1 << 24)"""The privilege to apply a policy."""+ VIEW_POLICY = (0, 1 << 35)+ """The privilege to view policy metadata, content, and associations."""+REGISTER_JOB_TEMPLATE = (0, 1 << 25)"""The privilege to register a job template."""@@ -1188,6 +1194,34 @@ class ApplyTag(GenericPrivilege):return obj_type in [MetadataObject.Type.METALAKE, MetadataObject.Type.TAG]+class ViewTag(GenericPrivilege):+ """The privilege to view tag metadata and associations."""++ _ALLOW_INSTANCE: Optional[ViewTag] = None+ _DENY_INSTANCE: Optional[ViewTag] = None++ @staticmethod+ def allow() -> Privilege:+ """Return the allow instance of the privilege."""+ if ViewTag._ALLOW_INSTANCE is None:+ ViewTag._ALLOW_INSTANCE = ViewTag(+ Privilege.Condition.ALLOW, Privilege.Name.VIEW_TAG+ )+ return ViewTag._ALLOW_INSTANCE++ @staticmethod+ def deny() -> Privilege:+ """Return the deny instance of the privilege."""+ if ViewTag._DENY_INSTANCE is None:+ ViewTag._DENY_INSTANCE = ViewTag(+ Privilege.Condition.DENY, Privilege.Name.VIEW_TAG+ )+ return ViewTag._DENY_INSTANCE++ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:+ return obj_type in [MetadataObject.Type.METALAKE, MetadataObject.Type.TAG]++class CreatePolicy(GenericPrivilege):"""The privilege to create a policy"""@@ -1312,6 +1346,34 @@ class ApplyPolicy(GenericPrivilege):return obj_type in [MetadataObject.Type.METALAKE, MetadataObject.Type.POLICY]+class ViewPolicy(GenericPrivilege):+ """The privilege to view policy metadata, content, and associations."""++ _ALLOW_INSTANCE: Optional[ViewPolicy] = None+ _DENY_INSTANCE: Optional[ViewPolicy] = None++ @staticmethod+ def allow() -> Privilege:+ """Return the allow instance of the privilege."""+ if ViewPolicy._ALLOW_INSTANCE is None:+ ViewPolicy._ALLOW_INSTANCE = ViewPolicy(+ Privilege.Condition.ALLOW, Privilege.Name.VIEW_POLICY+ )+ return ViewPolicy._ALLOW_INSTANCE++ @staticmethod+ def deny() -> Privilege:+ """Return the deny instance of the privilege."""+ if ViewPolicy._DENY_INSTANCE is None:+ ViewPolicy._DENY_INSTANCE = ViewPolicy(+ Privilege.Condition.DENY, Privilege.Name.VIEW_POLICY+ )+ return ViewPolicy._DENY_INSTANCE++ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:+ return obj_type in [MetadataObject.Type.METALAKE, MetadataObject.Type.POLICY]++class RegisterJobTemplate(GenericPrivilege):"""The privilege to register a job template"""@@ -1668,9 +1730,11 @@ class Privileges:Privilege.Name.USE_MODEL: UseModel,Privilege.Name.CREATE_TAG: CreateTag,Privilege.Name.APPLY_TAG: ApplyTag,+ Privilege.Name.VIEW_TAG: ViewTag,Privilege.Name.CREATE_POLICY: CreatePolicy,Privilege.Name.APPLY_POLICY: ApplyPolicy,Privilege.Name.VIEW_SECRET_PROVIDERS: ViewSecretProviders,+ Privilege.Name.VIEW_POLICY: ViewPolicy,Privilege.Name.REGISTER_JOB_TEMPLATE: RegisterJobTemplate,Privilege.Name.USE_JOB_TEMPLATE: UseJobTemplate,Privilege.Name.RUN_JOB: RunJob,diff --git a/clients/client-python/tests/unittests/authorization/test_privileges.py b/clients/client-python/tests/unittests/authorization/test_privileges.pyindex daa3317989..e50d137035 100644--- a/clients/client-python/tests/unittests/authorization/test_privileges.py+++ b/clients/client-python/tests/unittests/authorization/test_privileges.py@@ -53,6 +53,8 @@ from gravitino.api.authorization.privileges import (UseJobTemplate,UseModel,UseSchema,+ ViewPolicy,+ ViewTag,WriteFileset,)from gravitino.api.metadata_object import MetadataObject@@ -111,6 +113,10 @@ class TestPrivileges(unittest.TestCase):Privileges.deny("CREATE_MODEL_VERSION").name(),)+ def test_view_privilege_bit_values_match_java_api(self) -> None:+ self.assertEqual(1 << 34, Privilege.Name.VIEW_TAG.low_bits)+ self.assertEqual(1 << 35, Privilege.Name.VIEW_POLICY.low_bits)+def test_create_catalog_binding(self) -> None:allow_privilege = CreateCatalog.allow()for obj_type in MetadataObject.Type:@@ -311,6 +317,15 @@ class TestPrivileges(unittest.TestCase):deny_privilege.can_bind_to(obj_type),)+ def test_view_tag_binding(self) -> None:+ deny_privilege = ViewTag.deny()+ for obj_type in MetadataObject.Type:+ with self.subTest(obj_type=obj_type.name):+ self.assertEqual(+ obj_type in [MetadataObject.Type.METALAKE, MetadataObject.Type.TAG],+ deny_privilege.can_bind_to(obj_type),+ )+def test_create_policy_binding(self) -> None:deny_privilege = CreatePolicy.deny()for obj_type in MetadataObject.Type:@@ -339,6 +354,16 @@ class TestPrivileges(unittest.TestCase):deny_privilege.can_bind_to(obj_type),)+ def test_view_policy_binding(self) -> None:+ deny_privilege = ViewPolicy.deny()+ for obj_type in MetadataObject.Type:+ with self.subTest(obj_type=obj_type.name):+ self.assertEqual(+ obj_type+ in [MetadataObject.Type.METALAKE, MetadataObject.Type.POLICY],+ deny_privilege.can_bind_to(obj_type),+ )+def test_register_job_template_binding(self) -> None:deny_privilege = RegisterJobTemplate.deny()for obj_type in MetadataObject.Type:diff --git a/common/src/main/java/org/apache/gravitino/dto/policy/PolicyAssociationSelectorDTO.java b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyAssociationSelectorDTO.javanew file mode 100644index 0000000000..0175c1c2f3--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyAssociationSelectorDTO.java@@ -0,0 +1,108 @@+/*+ * 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.dto.policy;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import javax.annotation.Nullable;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.policy.AllValuesSelector;+import org.apache.gravitino.policy.PolicyAssociationSelector;+import org.apache.gravitino.policy.TagValueSelector;++/** Data transfer object for a policy-to-tag selector. */+@Getter+@ToString+@EqualsAndHashCode+public class PolicyAssociationSelectorDTO {++ private static final int MAX_VALUE_LENGTH = 256;++ @JsonProperty("type")+ private String type;++ @JsonInclude(JsonInclude.Include.NON_NULL)+ @JsonProperty("value")+ @Nullable+ private String value;++ private PolicyAssociationSelectorDTO() {}++ /**+ * Creates a selector DTO.+ *+ * @param type The selector type.+ * @param value The selector value, or null for {@link AllValuesSelector}.+ */+ public PolicyAssociationSelectorDTO(String type, @Nullable String value) {+ this.type = type;+ this.value = value;+ }++ /**+ * Creates a DTO from an API selector.+ *+ * @param selector The API selector.+ * @return The selector DTO.+ */+ public static PolicyAssociationSelectorDTO fromSelector(PolicyAssociationSelector selector) {+ Preconditions.checkArgument(selector != null, "Selector cannot be null");+ if (selector instanceof AllValuesSelector) {+ return new PolicyAssociationSelectorDTO(AllValuesSelector.TYPE, null);+ }+ if (selector instanceof TagValueSelector) {+ return new PolicyAssociationSelectorDTO(+ TagValueSelector.TYPE, ((TagValueSelector) selector).value());+ }+ throw new IllegalArgumentException("Unsupported selector type: " + selector.type());+ }++ /** Validates this selector DTO. */+ public void validate() {+ Preconditions.checkArgument(StringUtils.isNotBlank(type), "Selector type cannot be blank");+ if (AllValuesSelector.TYPE.equals(type)) {+ Preconditions.checkArgument(value == null, "ALL_VALUES selector must not define a value");+ return;+ }+ Preconditions.checkArgument(+ TagValueSelector.TYPE.equals(type), "Unsupported selector type: %s", type);+ Preconditions.checkArgument(StringUtils.isNotBlank(value), "Selector value cannot be blank");+ Preconditions.checkArgument(+ value.length() <= MAX_VALUE_LENGTH,+ "Selector value must not exceed %s characters",+ MAX_VALUE_LENGTH);+ }++ /**+ * Converts this DTO to an API selector.+ *+ * @return The API selector.+ */+ public PolicyAssociationSelector toSelector() {+ validate();+ if (AllValuesSelector.TYPE.equals(type)) {+ return AllValuesSelector.get();+ }+ return TagValueSelector.of(value);+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/policy/PolicyForTagAssociationDTO.java b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyForTagAssociationDTO.javanew file mode 100644index 0000000000..e2d6e42568--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyForTagAssociationDTO.java@@ -0,0 +1,52 @@+/*+ * 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.dto.policy;++import com.fasterxml.jackson.annotation.JsonProperty;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;++/** A policy and selector returned while listing associations for a tag. */+@Getter+@ToString+@EqualsAndHashCode+public class PolicyForTagAssociationDTO {++ @JsonProperty("policy")+ private final PolicyDTO policy;++ @JsonProperty("selector")+ private final PolicyAssociationSelectorDTO selector;++ /**+ * Creates a policy association DTO.+ *+ * @param policy The associated policy.+ * @param selector The policy association selector.+ */+ public PolicyForTagAssociationDTO(PolicyDTO policy, PolicyAssociationSelectorDTO selector) {+ this.policy = policy;+ this.selector = selector;+ }++ private PolicyForTagAssociationDTO() {+ this(null, null);+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/PolicyTagAddRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/PolicyTagAddRequest.javanew file mode 100644index 0000000000..adb0e2bfca--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/requests/PolicyTagAddRequest.java@@ -0,0 +1,64 @@+/*+ * 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.dto.requests;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import javax.annotation.Nullable;+import lombok.EqualsAndHashCode;+import lombok.ToString;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;+import org.apache.gravitino.policy.PolicyAssociationSelector;+import org.apache.gravitino.rest.RESTRequest;++/** Request to add one policy-to-tag association. */+@ToString+@EqualsAndHashCode+public class PolicyTagAddRequest implements RESTRequest {++ @JsonProperty("selector")+ @Nullable+ private PolicyAssociationSelectorDTO selector;++ /** Creates an empty request for Jackson deserialization. */+ public PolicyTagAddRequest() {}++ /**+ * Creates a request with a selector.+ *+ * @param selector The policy association selector.+ */+ public PolicyTagAddRequest(PolicyAssociationSelectorDTO selector) {+ this.selector = selector;+ }++ /**+ * @return The policy association selector.+ */+ public PolicyAssociationSelector selector() {+ Preconditions.checkArgument(selector != null, "selector must not be null");+ return selector.toSelector();+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(selector != null, "selector must not be null");+ selector.validate();+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/PolicyForTagAssociationListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/PolicyForTagAssociationListResponse.javanew file mode 100644index 0000000000..0e4f3e76ef--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/PolicyForTagAssociationListResponse.java@@ -0,0 +1,55 @@+/*+ * 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.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.gravitino.dto.policy.PolicyForTagAssociationDTO;++/** Response containing detailed policy associations for one tag. */+@Getter+@ToString+@EqualsAndHashCode(callSuper = true)+public class PolicyForTagAssociationListResponse extends BaseResponse {++ @JsonProperty("associations")+ private final PolicyForTagAssociationDTO[] associations;++ /**+ * Creates a response.+ *+ * @param associations The association details.+ */+ public PolicyForTagAssociationListResponse(PolicyForTagAssociationDTO[] associations) {+ this.associations = associations;+ }++ private PolicyForTagAssociationListResponse() {+ this(null);+ }++ @Override+ public void validate() throws IllegalArgumentException {+ super.validate();+ Preconditions.checkArgument(associations != null, "associations must not be null");+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/PolicyTagAssociationResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/PolicyTagAssociationResponse.javanew file mode 100644index 0000000000..84866596e5--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/PolicyTagAssociationResponse.java@@ -0,0 +1,70 @@+/*+ * 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.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;++/** Response for adding one policy-to-tag association. */+@Getter+@ToString+@EqualsAndHashCode(callSuper = true)+public class PolicyTagAssociationResponse extends BaseResponse {++ @JsonProperty("policy")+ private final String policy;++ @JsonProperty("tag")+ private final String tag;++ @JsonProperty("selector")+ private final PolicyAssociationSelectorDTO selector;++ /**+ * Creates a response.+ *+ * @param policy The policy name.+ * @param tag The tag name.+ * @param selector The policy association selector.+ */+ public PolicyTagAssociationResponse(+ String policy, String tag, PolicyAssociationSelectorDTO selector) {+ this.policy = policy;+ this.tag = tag;+ this.selector = selector;+ }++ private PolicyTagAssociationResponse() {+ this(null, null, null);+ }++ @Override+ public void validate() throws IllegalArgumentException {+ super.validate();+ Preconditions.checkArgument(StringUtils.isNotBlank(policy), "policy must not be blank");+ Preconditions.checkArgument(StringUtils.isNotBlank(tag), "tag must not be blank");+ Preconditions.checkArgument(selector != null, "selector must not be null");+ selector.validate();+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/TagForPolicyAssociationListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/TagForPolicyAssociationListResponse.javanew file mode 100644index 0000000000..bd3e34467b--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/TagForPolicyAssociationListResponse.java@@ -0,0 +1,55 @@+/*+ * 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.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.gravitino.dto.tag.TagForPolicyAssociationDTO;++/** Response containing detailed tag associations for one policy. */+@Getter+@ToString+@EqualsAndHashCode(callSuper = true)+public class TagForPolicyAssociationListResponse extends BaseResponse {++ @JsonProperty("associations")+ private final TagForPolicyAssociationDTO[] associations;++ /**+ * Creates a response.+ *+ * @param associations The association details.+ */+ public TagForPolicyAssociationListResponse(TagForPolicyAssociationDTO[] associations) {+ this.associations = associations;+ }++ private TagForPolicyAssociationListResponse() {+ this(null);+ }++ @Override+ public void validate() throws IllegalArgumentException {+ super.validate();+ Preconditions.checkArgument(associations != null, "associations must not be null");+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/tag/TagForPolicyAssociationDTO.java b/common/src/main/java/org/apache/gravitino/dto/tag/TagForPolicyAssociationDTO.javanew file mode 100644index 0000000000..8558a1e4b6--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/tag/TagForPolicyAssociationDTO.java@@ -0,0 +1,53 @@+/*+ * 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.dto.tag;++import com.fasterxml.jackson.annotation.JsonProperty;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;++/** A tag and selector returned while listing associations for a policy. */+@Getter+@ToString+@EqualsAndHashCode+public class TagForPolicyAssociationDTO {++ @JsonProperty("tag")+ private final TagDTO tag;++ @JsonProperty("selector")+ private final PolicyAssociationSelectorDTO selector;++ /**+ * Creates a tag association DTO.+ *+ * @param tag The associated tag.+ * @param selector The policy association selector.+ */+ public TagForPolicyAssociationDTO(TagDTO tag, PolicyAssociationSelectorDTO selector) {+ this.tag = tag;+ this.selector = selector;+ }++ private TagForPolicyAssociationDTO() {+ this(null, null);+ }+}diff --git a/common/src/test/java/org/apache/gravitino/dto/policy/TestPolicyAssociationSelectorDTO.java b/common/src/test/java/org/apache/gravitino/dto/policy/TestPolicyAssociationSelectorDTO.javanew file mode 100644index 0000000000..e8a76a1e79--- /dev/null+++ b/common/src/test/java/org/apache/gravitino/dto/policy/TestPolicyAssociationSelectorDTO.java@@ -0,0 +1,77 @@+/*+ * 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.dto.policy;++import com.fasterxml.jackson.core.JsonProcessingException;+import org.apache.gravitino.dto.requests.PolicyTagAddRequest;+import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.policy.AllValuesSelector;+import org.apache.gravitino.policy.TagValueSelector;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestPolicyAssociationSelectorDTO {++ @Test+ public void testAllValuesSelectorSerDe() throws JsonProcessingException {+ PolicyAssociationSelectorDTO selector =+ PolicyAssociationSelectorDTO.fromSelector(AllValuesSelector.get());++ String json = JsonUtils.objectMapper().writeValueAsString(selector);+ PolicyAssociationSelectorDTO deserialized =+ JsonUtils.objectMapper().readValue(json, PolicyAssociationSelectorDTO.class);++ Assertions.assertEquals(selector, deserialized);+ Assertions.assertFalse(json.contains("value"));+ Assertions.assertSame(AllValuesSelector.get(), deserialized.toSelector());+ }++ @Test+ public void testTagValueSelectorRequestSerDe() throws JsonProcessingException {+ PolicyAssociationSelectorDTO selector =+ PolicyAssociationSelectorDTO.fromSelector(TagValueSelector.of("finance"));+ PolicyTagAddRequest request = new PolicyTagAddRequest(selector);++ String json = JsonUtils.objectMapper().writeValueAsString(request);+ PolicyTagAddRequest deserialized =+ JsonUtils.objectMapper().readValue(json, PolicyTagAddRequest.class);++ deserialized.validate();+ Assertions.assertEquals(TagValueSelector.of("finance"), deserialized.selector());+ }++ @Test+ public void testInvalidSelectors() {+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> PolicyAssociationSelectorDTO.fromSelector(null));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new PolicyAssociationSelectorDTO("UNKNOWN", null).validate());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new PolicyAssociationSelectorDTO(AllValuesSelector.TYPE, "unexpected").validate());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new PolicyAssociationSelectorDTO(TagValueSelector.TYPE, " ").validate());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new PolicyAssociationSelectorDTO(TagValueSelector.TYPE, "a".repeat(257)).validate());+ Assertions.assertThrows(IllegalArgumentException.class, new PolicyTagAddRequest()::validate);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/meta/PolicyEntity.java b/core/src/main/java/org/apache/gravitino/meta/PolicyEntity.javaindex 2c122c3ca8..d306aaacef 100644--- a/core/src/main/java/org/apache/gravitino/meta/PolicyEntity.java+++ b/core/src/main/java/org/apache/gravitino/meta/PolicyEntity.java@@ -24,6 +24,7 @@ import java.util.Collections;import java.util.Map;import java.util.Objects;import java.util.Optional;+import javax.annotation.Nullable;import lombok.ToString;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Audit;@@ -65,6 +66,7 @@ public class PolicyEntity implements Entity, Auditable, HasIdentifier {private String comment;private boolean enabled;private PolicyContent content;+ @Nullable private Boolean inherited;private AuditInfo auditInfo;private PolicyEntity() {}@@ -125,7 +127,33 @@ public class PolicyEntity implements Entity, Auditable, HasIdentifier {}public Optional<Boolean> inherited() {- return Optional.empty();+ return Optional.ofNullable(inherited);+ }++ /**+ * Returns a copy of this policy entity with the given inheritance context.+ *+ * <p>The inheritance context records whether the policy was selected only from ancestor metadata+ * objects, either by an inherited tag assignment or a legacy direct policy association. It is not+ * part of the policy definition fields.+ *+ * @param inherited Whether the policy was selected only from ancestor metadata objects.+ * @return The copied policy entity with the inheritance context.+ */+ public PolicyEntity copyWithInherited(boolean inherited) {+ PolicyEntity copy =+ PolicyEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withPolicyType(policyType)+ .withComment(comment)+ .withEnabled(enabled)+ .withContent(content)+ .withAuditInfo(auditInfo)+ .build();+ copy.inherited = inherited;+ return copy;}@Overridediff --git a/core/src/main/java/org/apache/gravitino/meta/TagEntity.java b/core/src/main/java/org/apache/gravitino/meta/TagEntity.javaindex 2730f921c9..7049a5121e 100644--- a/core/src/main/java/org/apache/gravitino/meta/TagEntity.java+++ b/core/src/main/java/org/apache/gravitino/meta/TagEntity.java@@ -63,6 +63,7 @@ public class TagEntity implements Tag, Entity, Auditable, HasIdentifier {private Map<String, String> properties;private String[] allowedValues;@Nullable private TagAssignment assignment;+ @Nullable private Boolean inherited;private Audit auditInfo;private TagEntity() {}@@ -128,7 +129,7 @@ public class TagEntity implements Tag, Entity, Auditable, HasIdentifier {@Overridepublic Optional<Boolean> inherited() {- return Optional.empty();+ return Optional.ofNullable(inherited);}@Override@@ -172,16 +173,34 @@ public class TagEntity implements Tag, Entity, Auditable, HasIdentifier {* @return The copied tag entity with the assignment context.*/public TagEntity copyWithAssignment(@Nullable TagAssignment assignment) {- return TagEntity.builder()- .withId(id)- .withName(name)- .withNamespace(namespace)- .withComment(comment)- .withProperties(properties)- .withAllowedValues(allowedValues)- .withAssignment(assignment)- .withAuditInfo(auditInfo)- .build();+ TagEntity copy =+ TagEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withComment(comment)+ .withProperties(properties)+ .withAllowedValues(allowedValues)+ .withAssignment(assignment)+ .withAuditInfo(auditInfo)+ .build();+ copy.inherited = inherited;+ return copy;+ }++ /**+ * Returns a copy of this tag entity with the given inheritance context.+ *+ * <p>The inheritance context is used only when the tag is resolved for a metadata object; it is+ * not part of the tag definition fields.+ *+ * @param inherited Whether the tag assignment is inherited from an ancestor object.+ * @return The copied tag entity with the inheritance context.+ */+ public TagEntity copyWithInherited(boolean inherited) {+ TagEntity copy = copyWithAssignment(assignment);+ copy.inherited = inherited;+ return copy;}public static Builder builder() {diff --git a/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java b/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.javaindex c9b0f4a0fb..eb1676b7da 100644--- a/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java+++ b/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java@@ -42,8 +42,8 @@ import org.slf4j.LoggerFactory;/*** Resolves policies for a metadata object from its effective tag assignments.*- * <p>The resolver evaluates relation selectors, rejects mixed match results for the same policy,- * filters disabled policies, and deduplicates repeated matches by policy entity ID.+ * <p>The resolver evaluates relation selectors, filters disabled policies, and deduplicates+ * repeated matches by policy entity ID.*/public class ObjectPolicyResolver {@@ -119,13 +119,7 @@ public class ObjectPolicyResolver {boolean matches = matches(selector, assignment);MatchState state =matchStates.computeIfAbsent(policy.id(), ignored -> new MatchState(policy));- state.record(matches);- if (state.hasConflict()) {- throw new IllegalStateException(- String.format(- "Policy %s has conflicting selector results for metadata object %s",- policy.name(), metadataObject));- }+ state.record(matches, tag.inherited().orElse(false));}return matchStates.values().stream()@@ -151,19 +145,15 @@ public class ObjectPolicyResolver {private final PolicyEntity policy;private boolean matched;- private boolean unmatched;+ private boolean directMatch;private MatchState(PolicyEntity policy) {this.policy = policy;}- private void record(boolean matches) {+ private void record(boolean matches, boolean inherited) {matched |= matches;- unmatched |= !matches;- }-- private boolean hasConflict() {- return matched && unmatched;+ directMatch |= matches && !inherited;}private boolean matched() {@@ -171,7 +161,7 @@ public class ObjectPolicyResolver {}private PolicyEntity policy() {- return policy;+ return policy.copyWithInherited(!directMatch);}}}diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.javaindex e452110661..457a4a0b7c 100644--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java@@ -27,7 +27,9 @@ import java.io.IOException;import java.time.Instant;import java.util.Arrays;import java.util.Collections;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Map;import java.util.Set;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityAlreadyExistsException;@@ -71,6 +73,7 @@ public class PolicyManager implements PolicyDispatcher {private final IdGenerator idGenerator;private final EntityStore entityStore;+ private final ObjectPolicyResolver objectPolicyResolver;public PolicyManager(IdGenerator idGenerator, EntityStore entityStore) {if (!(entityStore instanceof SupportsRelationOperations)) {@@ -83,6 +86,7 @@ public class PolicyManager implements PolicyDispatcher {this.idGenerator = idGenerator;this.entityStore = entityStore;+ this.objectPolicyResolver = new ObjectPolicyResolver(entityStore);}@Override@@ -295,12 +299,30 @@ public class PolicyManager implements PolicyDispatcher {@Overridepublic PolicyEntity[] listPolicyInfosForMetadataObject(String metalake, MetadataObject metadataObject) {- NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);- Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);checkMetalake(NameIdentifier.of(metalake), entityStore);- return listDirectPoliciesForMetadataObject(entityIdent, entityType, metadataObject);+ Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();+ Arrays.stream(listDirectPoliciesForMetadataObject(metalake, metadataObject, false))+ .forEach(policy -> policiesById.put(policy.id(), policy));++ Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))+ .forEach(+ policy -> {+ if (policy.inherited().orElse(false)) {+ policiesById.putIfAbsent(policy.id(), policy);+ } else {+ policiesById.put(policy.id(), policy);+ }+ });++ for (MetadataObject parent : MetadataObjectUtil.getParentMetadataObjects(metadataObject)) {+ Arrays.stream(listDirectPoliciesForMetadataObject(metalake, parent, true))+ .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));+ }+ return policiesById.values().stream()+ .filter(PolicyEntity::enabled)+ .toArray(PolicyEntity[]::new);}@Override@@ -396,7 +418,9 @@ public class PolicyManager implements PolicyDispatcher {}private PolicyEntity[] listDirectPoliciesForMetadataObject(- NameIdentifier entityIdent, Entity.EntityType entityType, MetadataObject metadataObject) {+ String metalake, MetadataObject metadataObject, boolean inherited) {+ NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);+ Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);return TreeLockUtils.doWithTreeLock(entityIdent,LockType.READ,@@ -410,7 +434,7 @@ public class PolicyManager implements PolicyDispatcher {entityType,true /* allFields */).stream()- .map(entity -> (PolicyEntity) entity)+ .map(entity -> ((PolicyEntity) entity).copyWithInherited(inherited)).toArray(PolicyEntity[]::new);} catch (NoSuchEntityException e) {throw new NoSuchMetadataObjectException(diff --git a/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java b/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.javaindex 60b106cfe1..b446177add 100644--- a/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java+++ b/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java@@ -71,7 +71,9 @@ public class EffectiveTagResolver {resolutionOrder.addAll(MetadataObjectUtil.getParentMetadataObjects(metadataObject));Map<String, TagEntity> effectiveTags = new LinkedHashMap<>();- for (MetadataObject object : resolutionOrder) {+ for (int index = 0; index < resolutionOrder.size(); index++) {+ MetadataObject object = resolutionOrder.get(index);+ boolean inherited = index > 0;NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);try {@@ -82,7 +84,8 @@ public class EffectiveTagResolver {SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,identifier,entityType);- tags.forEach(tag -> effectiveTags.putIfAbsent(tag.name(), tag));+ tags.forEach(+ tag -> effectiveTags.putIfAbsent(tag.name(), tag.copyWithInherited(inherited)));} catch (NoSuchEntityException e) {throw new NoSuchMetadataObjectException(e, "Failed to resolve effective tags for metadata object %s due to not found", object);diff --git a/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java b/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.javaindex f418887299..d448b925d4 100644--- a/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java+++ b/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java@@ -66,8 +66,9 @@ public class TestObjectPolicyResolver {@Testpublic void testResolveByPresenceAndValueSelector() throws Exception {- TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance"));- TagEntity classified = tag(2L, "classified", TagAssignment.noValue());+ TagEntity domain =+ tag(1L, "domain", TagAssignment.ofValues("finance")).copyWithInherited(false);+ TagEntity classified = tag(2L, "classified", TagAssignment.noValue()).copyWithInherited(true);PolicyEntity selected = policy(10L, "selected", true);PolicyEntity disabled = policy(11L, "disabled", false);when(effectiveTagResolver.resolve(METALAKE, OBJECT))@@ -87,11 +88,12 @@ public class TestObjectPolicyResolver {PolicyEntity[] policies = resolver.resolve(METALAKE, OBJECT);Assertions.assertArrayEquals(new PolicyEntity[] {selected}, policies);+ Assertions.assertFalse(policies[0].inherited().orElseThrow());}@Testpublic void testResolveMissingSelectorAsAllValues() throws Exception {- TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance"));+ TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance")).copyWithInherited(true);PolicyEntity policy = policy(10L, "policy", true);when(effectiveTagResolver.resolve(METALAKE, OBJECT)).thenReturn(new TagEntity[] {domain});when(relationOperations.batchListEntitiesByRelation(@@ -107,7 +109,9 @@ public class TestObjectPolicyResolver {policy,null)));- Assertions.assertArrayEquals(new PolicyEntity[] {policy}, resolver.resolve(METALAKE, OBJECT));+ PolicyEntity[] policies = resolver.resolve(METALAKE, OBJECT);+ Assertions.assertArrayEquals(new PolicyEntity[] {policy}, policies);+ Assertions.assertTrue(policies[0].inherited().orElseThrow());}@Test@@ -126,7 +130,7 @@ public class TestObjectPolicyResolver {}@Test- public void testRejectMixedSelectorResults() throws Exception {+ public void testSelectPolicyWhenAnySelectorMatches() throws Exception {TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance"));TagEntity classified = tag(2L, "classified", TagAssignment.ofValues("public"));PolicyEntity policy = policy(10L, "policy", true);@@ -143,10 +147,7 @@ public class TestObjectPolicyResolver {relation(domain, policy, TagValueSelector.of("finance")),relation(classified, policy, TagValueSelector.of("pii"))));- IllegalStateException exception =- Assertions.assertThrows(- IllegalStateException.class, () -> resolver.resolve(METALAKE, OBJECT));- Assertions.assertTrue(exception.getMessage().contains("conflicting selector results"));+ Assertions.assertArrayEquals(new PolicyEntity[] {policy}, resolver.resolve(METALAKE, OBJECT));}private static RelationalEntity<PolicyEntity> relation(diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.javaindex 181af71e4a..425ea3d3f7 100644--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java@@ -91,6 +91,8 @@ import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.tag.TagManager;+import org.apache.gravitino.tag.TagValue;import org.apache.gravitino.utils.NameIdentifierUtil;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.AfterEach;@@ -122,6 +124,7 @@ public class TestPolicyManager {private static EntityStore entityStore;private static PolicyManager policyManager;+ private static TagManager tagManager;@BeforeAllpublic static void setUp() throws IllegalAccessException, IOException {@@ -130,6 +133,7 @@ public class TestPolicyManager {entityStore = EntityStoreFactory.createEntityStore(config);entityStore.initialize(config);policyManager = new PolicyManager(idGenerator, entityStore);+ tagManager = new TagManager(idGenerator, entityStore);FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);FieldUtils.writeField(@@ -274,6 +278,8 @@ public class TestPolicyManager {public void cleanUp() {Arrays.stream(policyManager.listPolicies(METALAKE)).forEach(policyName -> policyManager.deletePolicy(METALAKE, policyName));+ Arrays.stream(tagManager.listTags(METALAKE))+ .forEach(tagName -> tagManager.deleteTag(METALAKE, tagName));}@Test@@ -722,45 +728,45 @@ public class TestPolicyManager {NameIdentifierUtil.toMetadataObject(NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);+ associatePolicyThroughTag(policy1, catalogObject);+ associatePolicyThroughTag(policy2, schemaObject);+ associatePolicyThroughTag(policy3, tableObject);++ // Legacy direct object-policy relations remain readable during the compatibility window.policyManager.associatePoliciesForMetadataObject(- METALAKE,- catalogObject,- new String[] {policy1.name(), policy2.name(), policy3.name()},- null);- policyManager.associatePoliciesForMetadataObject(- METALAKE, schemaObject, new String[] {policy1.name(), policy2.name()}, null);- policyManager.associatePoliciesForMetadataObject(- METALAKE, tableObject, new String[] {policy1.name()}, null);+ METALAKE, catalogObject, new String[] {policy3.name()}, null);String[] policies = policyManager.listPoliciesForMetadataObject(METALAKE, catalogObject);- Assertions.assertEquals(3, policies.length);+ Assertions.assertEquals(2, policies.length);Assertions.assertEquals(- ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies));+ ImmutableSet.of(policyName1, policyName3), ImmutableSet.copyOf(policies));PolicyEntity[] policiesInfo =policyManager.listPolicyInfosForMetadataObject(METALAKE, catalogObject);- Assertions.assertEquals(3, policiesInfo.length);- Assertions.assertEquals(- ImmutableSet.of(policy1, policy2, policy3), ImmutableSet.copyOf(policiesInfo));+ Assertions.assertEquals(2, policiesInfo.length);+ Assertions.assertEquals(ImmutableSet.of(policy1, policy3), ImmutableSet.copyOf(policiesInfo));String[] policies1 = policyManager.listPoliciesForMetadataObject(METALAKE, schemaObject);- Assertions.assertEquals(2, policies1.length);+ Assertions.assertEquals(3, policies1.length);Assertions.assertEquals(- ImmutableSet.of(policyName1, policyName2), ImmutableSet.copyOf(policies1));+ ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies1));PolicyEntity[] policiesInfo1 =policyManager.listPolicyInfosForMetadataObject(METALAKE, schemaObject);- Assertions.assertEquals(2, policiesInfo1.length);- Assertions.assertEquals(ImmutableSet.of(policy1, policy2), ImmutableSet.copyOf(policiesInfo1));+ Assertions.assertEquals(3, policiesInfo1.length);+ Assertions.assertEquals(+ ImmutableSet.of(policy1, policy2, policy3), ImmutableSet.copyOf(policiesInfo1));String[] policies2 = policyManager.listPoliciesForMetadataObject(METALAKE, tableObject);- Assertions.assertEquals(1, policies2.length);- Assertions.assertEquals(ImmutableSet.of(policyName1), ImmutableSet.copyOf(policies2));+ Assertions.assertEquals(3, policies2.length);+ Assertions.assertEquals(+ ImmutableSet.of(policyName1, policyName2, policyName3), ImmutableSet.copyOf(policies2));PolicyEntity[] policiesInfo2 =policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject);- Assertions.assertEquals(1, policiesInfo2.length);- Assertions.assertEquals(ImmutableSet.of(policy1), ImmutableSet.copyOf(policiesInfo2));+ Assertions.assertEquals(3, policiesInfo2.length);+ Assertions.assertEquals(+ ImmutableSet.of(policy1, policy2, policy3), ImmutableSet.copyOf(policiesInfo2));// List policies for non-existent metadata objectMetadataObject nonExistentObject =@@ -772,8 +778,77 @@ public class TestPolicyManager {NotFoundException.class,() -> policyManager.listPoliciesForMetadataObject(METALAKE, nonExistentObject));Assertions.assertTrue(- e.getMessage()- .contains("Failed to list policies for metadata object " + nonExistentObject));+ e.getMessage().contains("non_existent_catalog"), "Actual message: " + e.getMessage());+ }++ @Test+ public void testDisabledPoliciesAreExcludedFromMetadataObjectResults() {+ PolicyContent content =+ PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null);+ String directPolicyName = "disabled_direct_" + UUID.randomUUID().toString().replace("-", "");+ PolicyEntity directPolicy =+ policyManager.createPolicy(+ METALAKE, directPolicyName, Policy.BuiltInType.CUSTOM, null, false, content);+ String tagPolicyName = "disabled_tag_" + UUID.randomUUID().toString().replace("-", "");+ PolicyEntity tagPolicy =+ policyManager.createPolicy(+ METALAKE, tagPolicyName, Policy.BuiltInType.CUSTOM, null, false, content);+ MetadataObject tableObject =+ NameIdentifierUtil.toMetadataObject(+ NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);++ policyManager.associatePoliciesForMetadataObject(+ METALAKE, tableObject, new String[] {directPolicy.name()}, null);+ associatePolicyThroughTag(tagPolicy, tableObject);++ Assertions.assertEquals(+ 0, policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject).length);+ Assertions.assertThrows(+ NoSuchPolicyException.class,+ () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, directPolicy.name()));+ Assertions.assertThrows(+ NoSuchPolicyException.class,+ () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, tagPolicy.name()));++ policyManager.enablePolicy(METALAKE, directPolicy.name());+ policyManager.enablePolicy(METALAKE, tagPolicy.name());++ Assertions.assertEquals(+ ImmutableSet.of(directPolicy.name(), tagPolicy.name()),+ ImmutableSet.copyOf(policyManager.listPoliciesForMetadataObject(METALAKE, tableObject)));+ }++ @Test+ public void testChildTagValueOverridesParentPolicySelector() {+ String policyName = "policy_" + UUID.randomUUID().toString().replace("-", "");+ PolicyEntity policy =+ createCustomPolicy(+ METALAKE,+ policyName,+ PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null));+ String tagName = "tag_" + UUID.randomUUID().toString().replace("-", "");+ tagManager.createTag(METALAKE, tagName, null, null);+ tagManager.addPolicyForTag(METALAKE, tagName, policy.name(), TagValueSelector.of("finance"));++ MetadataObject schemaObject =+ NameIdentifierUtil.toMetadataObject(+ NameIdentifierUtil.ofSchema(METALAKE, CATALOG, SCHEMA), Entity.EntityType.SCHEMA);+ MetadataObject tableObject =+ NameIdentifierUtil.toMetadataObject(+ NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);+ tagManager.associateTagValuesForMetadataObject(+ METALAKE, schemaObject, new TagValue[] {TagValue.of(tagName, "finance")}, null);+ tagManager.associateTagValuesForMetadataObject(+ METALAKE, tableObject, new TagValue[] {TagValue.of(tagName, "risk")}, null);++ Assertions.assertArrayEquals(+ new PolicyEntity[] {policy},+ policyManager.listPolicyInfosForMetadataObject(METALAKE, schemaObject));+ Assertions.assertEquals(+ 0, policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject).length);+ Assertions.assertThrows(+ NoSuchPolicyException.class,+ () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policyName));}@Test@@ -797,32 +872,39 @@ public class TestPolicyManager {NameIdentifierUtil.toMetadataObject(NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);+ associatePolicyThroughTag(policy1, catalogObject);+ associatePolicyThroughTag(policy2, schemaObject);+ associatePolicyThroughTag(policy3, tableObject);++ // Keep one legacy direct relation to verify it remains readable during the compatibility+ // window.policyManager.associatePoliciesForMetadataObject(- METALAKE, catalogObject, new String[] {policyName1, policyName2, policyName3}, null);- policyManager.associatePoliciesForMetadataObject(- METALAKE, schemaObject, new String[] {policyName1, policyName2}, null);- policyManager.associatePoliciesForMetadataObject(- METALAKE, tableObject, new String[] {policyName1}, null);+ METALAKE, catalogObject, new String[] {policyName3}, null);PolicyEntity result =policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policyName1);Assertions.assertEquals(policy1, result);+ Assertions.assertFalse(result.inherited().orElseThrow());PolicyEntity result1 =- policyManager.getPolicyForMetadataObject(METALAKE, schemaObject, policyName1);+ policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policyName1);Assertions.assertEquals(policy1, result1);+ Assertions.assertTrue(result1.inherited().orElseThrow());PolicyEntity result2 =- policyManager.getPolicyForMetadataObject(METALAKE, schemaObject, policy2.name());+ policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy2.name());Assertions.assertEquals(policy2, result2);+ Assertions.assertTrue(result2.inherited().orElseThrow());PolicyEntity result3 =- policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policy3.name());+ policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy3.name());Assertions.assertEquals(policy3, result3);+ Assertions.assertFalse(result3.inherited().orElseThrow());PolicyEntity result4 =policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy1.name());Assertions.assertEquals(policy1, result4);+ Assertions.assertTrue(result4.inherited().orElseThrow());// Test get non-existent policy for metadata objectThrowable e =@@ -833,18 +915,16 @@ public class TestPolicyManager {METALAKE, catalogObject, "non_existent_policy"));Assertions.assertTrue(e.getMessage().contains("Policy non_existent_policy does not exist"));- Throwable e1 =- Assertions.assertThrows(- NoSuchPolicyException.class,- () -> policyManager.getPolicyForMetadataObject(METALAKE, schemaObject, policy3.name()));- Assertions.assertTrue(- e1.getMessage().contains("Policy " + policyName3 + " does not exist"),- "Actual message: " + e1.getMessage());+ PolicyEntity directResult =+ policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policy3.name());+ Assertions.assertEquals(policy3, directResult);+ Assertions.assertFalse(directResult.inherited().orElseThrow());Throwable e2 =Assertions.assertThrows(NoSuchPolicyException.class,- () -> policyManager.getPolicyForMetadataObject(METALAKE, tableObject, policy2.name()));+ () ->+ policyManager.getPolicyForMetadataObject(METALAKE, catalogObject, policy2.name()));Assertions.assertTrue(e2.getMessage().contains("Policy " + policyName2 + " does not exist"),"Actual message: " + e2.getMessage());@@ -869,4 +949,12 @@ public class TestPolicyManager {return policyManager.createPolicy(metalakeName, policyName, Policy.BuiltInType.CUSTOM, null, true, policyContent);}++ private void associatePolicyThroughTag(PolicyEntity policy, MetadataObject metadataObject) {+ String tagName = "tag_" + UUID.randomUUID().toString().replace("-", "");+ tagManager.createTag(METALAKE, tagName, null, null);+ tagManager.addPolicyForTag(METALAKE, tagName, policy.name(), AllValuesSelector.get());+ tagManager.associateTagsForMetadataObject(+ METALAKE, metadataObject, new String[] {tagName}, null);+ }}diff --git a/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java b/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.javaindex b4d3ba7cc6..7f633218ed 100644--- a/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java+++ b/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java@@ -102,6 +102,9 @@ public class TestEffectiveTagResolver {new TagEntity[] {directDomain, schemaClassification, catalogOwner}, effectiveTags);Assertions.assertArrayEquals(new String[] {"finance"}, effectiveTags[0].assignment().orElseThrow().values());+ Assertions.assertFalse(effectiveTags[0].inherited().orElseThrow());+ Assertions.assertTrue(effectiveTags[1].inherited().orElseThrow());+ Assertions.assertTrue(effectiveTags[2].inherited().orElseThrow());}@Testdiff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.javaindex c3f3a8b20a..1451e2fc95 100644--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java@@ -1146,10 +1146,10 @@ public class TestTagManager {tagManager.removePolicyFromTag(METALAKE, tagName, policyName);Assertions.assertEquals(0, tagManager.listPolicyAssociationsForTag(METALAKE, tagName).length);- tagManager.addPolicyForTag(METALAKE, tagName, policyName, TagValueSelector.of("finance"));+ tagManager.addPolicyForTag(METALAKE, tagName, policyName, TagValueSelector.of("engineering"));associations = tagManager.listPolicyAssociationsForTag(METALAKE, tagName);Assertions.assertEquals(- TagValueSelector.of("finance"),+ TagValueSelector.of("engineering"),PolicyAssociationSelectorSerde.deserialize(associations[0].relationValue().orElseThrow()));tagManager.removePolicyFromTag(METALAKE, tagName, policyName);diff --git a/design-docs/policy-on-tag.md b/design-docs/policy-on-tag.mdindex 475f96ba28..8e6fb6df5a 100644--- a/design-docs/policy-on-tag.md+++ b/design-docs/policy-on-tag.md@@ -312,12 +312,15 @@ Constraints and indexes:`selector` rules:-1. `selector` is required and must not be null.+1. New associations require a non-null `selector`. Persisted null selector values are read as+ `ALL_VALUES` for storage compatibility.2. `ALL_VALUES` matches whenever the effective tag assignment exists.3. `TAG_VALUE` matches when the effective tag assignment contains the same value as`selector.value`.4. `TAG_VALUE` contains one non-blank `value` string.-5. If the tag defines allowed values, the selector value must be one of the allowed values.+5. `TAG_VALUE` selector validation is syntactic only and is independent of the tag's current+ allowed values. A selector that cannot match a current effective assignment remains valid but+ does not select the policy.6. Selector JSON is canonicalized before storage and comparison.7. The first version supports `ALL_VALUES` and `TAG_VALUE`. It does not support value absence,negative matching, principals, scopes, or general expressions. Future versions can add new@@ -565,17 +568,23 @@ corresponding view privileges."name": "iceberg_compaction_standard","policyType": "system_iceberg_compaction","enabled": true,+ "inherited": true,"content": {}}]}```-**Behavior:** Resolves object policies for one metadata object from its effective tags. Returns+**Behavior:** Resolves object policies for one metadata object from its effective tags and includes+legacy direct policy relations during the compatibility window. Returns`404 Not Found` if the metadata object does not exist. This endpoint is read-only and does notmodify policy objects or object-policy relationships. The caller must be authorized to access themetadata object. Resolved policies for which the caller lacks `VIEW_POLICY` are filtered from bothresponse shapes. `APPLY_POLICY` implies `VIEW_POLICY` for backward compatibility.+With `details=true`, `inherited` is `true` when every source of the policy comes from an ancestor+metadata object, whether through inherited effective tags or legacy direct policy relations. It is+`false` when at least one source is a tag assignment or legacy direct policy relation on the+requested object.A single policy can be associated with multiple effective tags on the same object. The resolverdeduplicates by policy entity and current version, not by equivalent policy content. Different@@ -597,21 +606,25 @@ the requested metadata object; if no direct relation exists, it searches parentmarks a parent result as inherited. The current post API atomically adds and removes direct policyrelations on the requested metadata object using `policiesToAdd` and `policiesToRemove`.-**New behavior:** `GET /api/metalakes/{metalake}/objects/{type}/{fullName}/policies` becomes a-read-only derived object policy lookup API. It does not read direct policy relations and does not-modify policy objects or object-policy relationships.+**Compatibility behavior:** During the compatibility window, object-policy GET APIs merge policies+resolved from the requested object's effective tags with legacy direct policy relations on the+requested object and its ancestors. Tag-derived policies are resolved exactly once for the+requested object. Results are deduplicated by policy entity ID, and a direct result on the requested+object takes precedence over an inherited result. The deprecated POST remains readable through the+same GET APIs, so an acknowledged legacy write is not silently ignored.-Direct object policy mutation and direct object-policy-detail APIs are removed from the target-model:+Direct object policy mutation and direct object-policy-detail APIs will be removed after the+compatibility window:```httpGET /api/metalakes/{metalake}/objects/{type}/{fullName}/policies/{policy}POST /api/metalakes/{metalake}/objects/{type}/{fullName}/policies```-**Migration impact:** Callers must use policy-to-tag association APIs and read object policies from-`GET /api/metalakes/{metalake}/objects/{type}/{fullName}/policies`. Object-side policy association-calls must be replaced with tag assignment calls.+**Migration impact:** Callers should move to policy-to-tag association APIs and read object policies+from `GET /api/metalakes/{metalake}/objects/{type}/{fullName}/policies`. Object-side policy+association calls must be replaced with tag assignment calls before the compatibility APIs are+removed.### Client API Changes@@ -662,10 +675,12 @@ The new privileges follow the existing allow and deny model. A grant on a metalapolicies or tags in that metalake. A grant on one policy or tag applies only to that entity. Metalakeowners and entity owners retain view access.-For backward compatibility, an effective `APPLY_POLICY` grant implies `VIEW_POLICY`, and an-effective `APPLY_TAG` grant implies `VIEW_TAG`. Existing roles with apply privileges therefore keep-their current read access without a grant migration. A corresponding explicit deny of the view-privilege blocks response visibility but does not change server-side policy enforcement.+For backward compatibility, an effective `APPLY_POLICY` grant provides policy read access, and an+effective `APPLY_TAG` grant provides tag read access. Existing roles with apply privileges therefore+keep their current read access without a grant migration. View and apply denies are evaluated+independently: `DENY_VIEW_POLICY` does not revoke read access provided by an effective+`APPLY_POLICY` grant, and `DENY_APPLY_POLICY` does not revoke access provided by an effective+`VIEW_POLICY` grant. The same rules apply to `VIEW_TAG` and `APPLY_TAG`.Recommended authorization rules:@@ -727,9 +742,9 @@ may still be covered by normal REST access logs or audit logs if the project recdeduplication. It does not make allow or deny decisions for row filters, column masks, or otherengine-enforced policy types.-The resolver must also detect mixed selector results for the same policy. This conflict exists when-one metadata object has multiple effective tags associated with the same policy and evaluation of-those policy-to-tag relation selectors produces at least one match and at least one non-match.+When one policy is associated with multiple effective tags, each relation selector independently+determines whether that relation selects the policy. The policy is selected if at least one relation+matches. Non-matching relations do not negate matching relations.For example:@@ -742,10 +757,9 @@ object effective tags:data_domain = ["risk"] -> not match```-For this object, `mask_policy` is both selected and not selected through different effective tag-relations, so the resolver detects a selector conflict. Relations for tags that are not in the-object's effective tag set do not participate in this detection. This design identifies the-conflict but does not define a precedence or merge rule for it.+For this object, the `classification` relation selects `mask_policy`; the non-matching+`data_domain` relation is ignored. Relations for tags that are not in the object's effective tag+set do not participate in selection.For row filter and column mask policies, enforcement consumers must fail closed if multipledistinct effective policies of the same kind apply to the same evaluation target. The system should@@ -775,7 +789,9 @@ Rules:2. If a system iceberg compaction policy appears in the object policy result, TMS uses its content.3. A system iceberg compaction policy uses `ALL_VALUES` for tag-presence behavior or a simple`TAG_VALUE` selector when maintenance behavior should depend on assignment values.-4. TMS does not read direct object policy relations.+4. During the compatibility window, TMS may receive legacy direct object policies through the+ merged object-policy result. After direct policy APIs are retired, only tag-derived policies+ remain.### User Process@@ -823,8 +839,8 @@ tag handling, direct-assignment override behavior, value grouping, and determini### Migration Process-This design is a breaking model change. The target runtime does not read direct object policy-relations.+This design is a breaking model change. The compatibility runtime reads direct object policy+relations together with tag-derived policies; the target runtime does not read direct relations.1. Inventory existing direct policy relations from `policy_relation_meta`, including inheritedrelations that users depend on through parent metadata objects.diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yamlindex 5af0739eb1..63ef9c0651 100644--- a/docs/open-api/openapi.yaml+++ b/docs/open-api/openapi.yaml@@ -75,6 +75,12 @@ paths:/metalakes/{metalake}/tags/{tag}:$ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1tags~1%7Btag%7D"+ /metalakes/{metalake}/tags/{tag}/policies:+ $ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1tags~1%7Btag%7D~1policies"++ /metalakes/{metalake}/tags/{tag}/policies/{policy}:+ $ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1tags~1%7Btag%7D~1policies~1%7Bpolicy%7D"+/metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/tags:$ref: "./tags.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7BmetadataObjectType%7D~1%7BmetadataObjectFullName%7D~1tags"@@ -96,6 +102,9 @@ paths:/metalakes/{metalake}/policies/{policy}/objects:$ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1policies~1%7Bpolicy%7D~1objects"+ /metalakes/{metalake}/policies/{policy}/tags:+ $ref: "./policies.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1policies~1%7Bpolicy%7D~1tags"+/metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/roles:$ref: "./roles.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7BmetadataObjectType%7D~1%7BmetadataObjectFullName%7D~1roles"diff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yamlindex 076b1e6464..55efb0f824 100644--- a/docs/open-api/policies.yaml+++ b/docs/open-api/policies.yaml@@ -365,6 +365,38 @@ paths:$ref: "./openapi.yaml#/components/responses/ServerErrorResponse"+ /metalakes/{metalake}/policies/{policy}/tags:+ parameters:+ - $ref: "./openapi.yaml#/components/parameters/metalake"+ - $ref: "./openapi.yaml#/components/parameters/policy"+ get:+ tags:+ - policy+ summary: List tags associated with a policy+ operationId: listTagsForPolicy+ parameters:+ - $ref: "#/components/parameters/details"+ responses:+ "200":+ description: Returns tag names or detailed policy-tag associations+ content:+ application/vnd.gravitino.v1+json:+ schema:+ oneOf:+ - $ref: "./openapi.yaml#/components/schemas/NameListResponse"+ - $ref: "#/components/schemas/TagForPolicyAssociationListResponse"+ "400":+ $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"+ "404":+ description: Not Found - The specified metalake or policy does not exist+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"+ "5xx":+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"++components:parameters:details:@@ -378,6 +410,47 @@ components:schemas:+ PolicyAssociationSelector:+ type: object+ required:+ - type+ properties:+ type:+ type: string+ description: The selector type used to match tag assignments+ enum: ["ALL_VALUES", "TAG_VALUE"]+ value:+ type: string+ description: The assignment value required by a TAG_VALUE selector+ nullable: true+ maxLength: 256++ TagForPolicyAssociation:+ type: object+ required:+ - tag+ - selector+ properties:+ tag:+ $ref: "./tags.yaml#/components/schemas/Tag"+ selector:+ $ref: "#/components/schemas/PolicyAssociationSelector"++ TagForPolicyAssociationListResponse:+ type: object+ required:+ - code+ - associations+ properties:+ code:+ type: integer+ format: int32+ enum: [0]+ associations:+ type: array+ items:+ $ref: "#/components/schemas/TagForPolicyAssociation"+PolicyContentBase:type: objectdescription: A base content structure for policies@@ -441,7 +514,8 @@ components:$ref: "./openapi.yaml#/components/schemas/Audit"inherited:type: boolean- description: Whether the policy is inherited from the parent metadata object+ description: Whether the policy is selected only from ancestor metadata objects, either+ through inherited tags or legacy direct policy associationsnullable: trueCustomPolicy:diff --git a/docs/open-api/tags.yaml b/docs/open-api/tags.yamlindex c9ea86cbf8..37c0cceec9 100644--- a/docs/open-api/tags.yaml+++ b/docs/open-api/tags.yaml@@ -380,6 +380,94 @@ paths:$ref: "./openapi.yaml#/components/responses/ServerErrorResponse"+ /metalakes/{metalake}/tags/{tag}/policies:+ parameters:+ - $ref: "./openapi.yaml#/components/parameters/metalake"+ - $ref: "./openapi.yaml#/components/parameters/tag"+ get:+ tags:+ - tag+ summary: List policies associated with a tag+ operationId: listPoliciesForTag+ parameters:+ - $ref: "#/components/parameters/details"+ responses:+ "200":+ description: Returns policy names or detailed policy-tag associations+ content:+ application/vnd.gravitino.v1+json:+ schema:+ oneOf:+ - $ref: "./openapi.yaml#/components/schemas/NameListResponse"+ - $ref: "#/components/responses/PolicyForTagAssociationListResponse"+ "400":+ $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"+ "404":+ description: Not Found - The specified metalake or tag does not exist+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"+ "5xx":+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"++ /metalakes/{metalake}/tags/{tag}/policies/{policy}:+ parameters:+ - $ref: "./openapi.yaml#/components/parameters/metalake"+ - $ref: "./openapi.yaml#/components/parameters/tag"+ - $ref: "./openapi.yaml#/components/parameters/policy"+ post:+ tags:+ - tag+ summary: Associate a policy with a tag+ operationId: addPolicyForTag+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/requests/PolicyTagAddRequest"+ responses:+ "200":+ description: Returns the created policy-tag association+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "#/components/responses/PolicyTagAssociationResponse"+ "400":+ $ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"+ "404":+ description: Not Found - The specified metalake, tag, or policy does not exist+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"+ "409":+ description: Conflict - The policy is already associated with the tag+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"+ "5xx":+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"+ delete:+ tags:+ - tag+ summary: Remove a policy association from a tag+ operationId: removePolicyFromTag+ responses:+ "204":+ description: The policy-tag association was removed+ "404":+ description: Not Found - The specified metalake, tag, or policy does not exist+ content:+ application/vnd.gravitino.v1+json:+ schema:+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"+ "5xx":+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"++components:parameters:details:@@ -467,6 +555,14 @@ components:requests:+ PolicyTagAddRequest:+ type: object+ required:+ - selector+ properties:+ selector:+ $ref: "./policies.yaml#/components/schemas/PolicyAssociationSelector"+TagCreateRequest:type: objectrequired:@@ -642,6 +738,48 @@ components:maxLength: 256responses:+ PolicyForTagAssociationListResponse:+ type: object+ required:+ - code+ - associations+ properties:+ code:+ type: integer+ format: int32+ enum: [0]+ associations:+ type: array+ items:+ type: object+ required:+ - policy+ - selector+ properties:+ policy:+ $ref: "./policies.yaml#/components/schemas/Policy"+ selector:+ $ref: "./policies.yaml#/components/schemas/PolicyAssociationSelector"++ PolicyTagAssociationResponse:+ type: object+ required:+ - code+ - policy+ - tag+ - selector+ properties:+ code:+ type: integer+ format: int32+ enum: [0]+ policy:+ type: string+ tag:+ type: string+ selector:+ $ref: "./policies.yaml#/components/schemas/PolicyAssociationSelector"+TagListResponse:type: objectproperties:diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.javaindex 705025153e..8bb75fa0d0 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java@@ -322,14 +322,14 @@ public class AuthorizationExpressionConstants {"METALAKE::OWNER || METALAKE::MANAGE_GROUPS || GROUP::SELF";public static final String LOAD_TAG_AUTHORIZATION_EXPRESSION =- "METALAKE::OWNER || TAG::OWNER || ANY_APPLY_TAG";+ "METALAKE::OWNER || TAG::OWNER || ANY_VIEW_TAG || ANY_APPLY_TAG";public static final String APPLY_TAG_AUTHORIZATION_EXPRESSION ="METALAKE::OWNER || TAG::OWNER || ANY_APPLY_TAG";public static final String LOAD_POLICY_AUTHORIZATION_EXPRESSION ="""- METALAKE::OWNER || POLICY::OWNER || ANY_APPLY_POLICY+ METALAKE::OWNER || POLICY::OWNER || ANY_VIEW_POLICY || ANY_APPLY_POLICY""";/**diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.javaindex e64e0f057f..82c54c5574 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java@@ -350,6 +350,15 @@ public class AuthorizationExpressionConverter {"ANY_WRITE_FILESET","((ANY(WRITE_FILESET, METALAKE, CATALOG, SCHEMA, FILESET))"+ "&& !(ANY(DENY_WRITE_FILESET, METALAKE, CATALOG, SCHEMA, FILESET)))");+ expression =+ expression.replaceAll(+ "ANY_VIEW_TAG",+ "((ANY(VIEW_TAG, METALAKE, TAG))" + " && !(ANY(DENY_VIEW_TAG, METALAKE, TAG)))");+ expression =+ expression.replaceAll(+ "ANY_VIEW_POLICY",+ "((ANY(VIEW_POLICY, METALAKE, POLICY))"+ + " && !(ANY(DENY_VIEW_POLICY, METALAKE, POLICY)))");expression =expression.replaceAll("ANY_APPLY_TAG",diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.javaindex 80f7326edd..d176ffdbbc 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java@@ -139,4 +139,19 @@ public class TestAuthorizationExpressionConverter {+ " VIEW, TOPIC, FILESET, MODEL, MODEL_VERSION)))",replaced);}++ @Test+ public void testReplaceAnyPrivilegeForAnyViewTag() {+ String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_VIEW_TAG");+ Assertions.assertEquals(+ "((ANY(VIEW_TAG, METALAKE, TAG)) && !(ANY(DENY_VIEW_TAG, METALAKE, TAG)))", replaced);+ }++ @Test+ public void testReplaceAnyPrivilegeForAnyViewPolicy() {+ String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_VIEW_POLICY");+ Assertions.assertEquals(+ "((ANY(VIEW_POLICY, METALAKE, POLICY)) && !(ANY(DENY_VIEW_POLICY, METALAKE, POLICY)))",+ replaced);+ }}diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.javaindex 471e1acecd..0a545267d5 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java@@ -831,6 +831,9 @@ public class ExceptionHandlers {} else if (e instanceof TagAlreadyAssociatedException) {return Utils.alreadyExists(errorMsg, e);+ } else if (e instanceof PolicyAlreadyAssociatedException) {+ return Utils.alreadyExists(errorMsg, e);+} else if (e instanceof NotInUseException) {return Utils.notInUse(errorMsg, e);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.javaindex 19ea45ab96..bd01f76a75 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java@@ -22,12 +22,9 @@ import static org.apache.gravitino.server.authorization.expression.Authorizationimport com.codahale.metrics.annotation.ResponseMetered;import com.codahale.metrics.annotation.Timed;-import com.google.common.collect.Sets;import java.util.Arrays;-import java.util.Collections;import java.util.Locale;import java.util.Optional;-import java.util.Set;import javax.inject.Inject;import javax.servlet.http.HttpServletRequest;import javax.ws.rs.DefaultValue;@@ -39,7 +36,6 @@ import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.Context;import javax.ws.rs.core.Response;-import org.apache.commons.lang3.ArrayUtils;import org.apache.gravitino.Entity;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;@@ -60,7 +56,6 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationObjectimport org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.apache.gravitino.server.web.Utils;-import org.apache.gravitino.utils.MetadataObjectUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -85,7 +80,7 @@ public class MetadataObjectPolicyOperations {@ResponseMetered(name = "get-object-policy", absolute = true)@AuthorizationExpression(expression =- "METALAKE::OWNER || ((POLICY::OWNER || ANY_APPLY_POLICY) && (CAN_ACCESS_METADATA))")+ "METALAKE::OWNER || ((POLICY::OWNER || ANY_VIEW_POLICY || ANY_APPLY_POLICY) && (CAN_ACCESS_METADATA))")public Response getPolicyForObject(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,@@ -109,16 +104,10 @@ public class MetadataObjectPolicyOperations {fullName, MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));Optional<PolicyEntity> policyEntity = getPolicyForObject(metalake, object, policyName);Optional<PolicyDTO> policyDTO =- policyEntity.map(t -> PolicyOperations.toDTO(t, Optional.of(false)));-- for (MetadataObject parentObject :- MetadataObjectUtil.getParentMetadataObjects(object)) {- if (policyEntity.isPresent()) {- break;- }- policyEntity = getPolicyForObject(metalake, parentObject, policyName);- policyDTO = policyEntity.map(t -> PolicyOperations.toDTO(t, Optional.of(true)));- }+ policyEntity.map(+ policy ->+ PolicyOperations.toDTO(+ policy, Optional.of(policy.inherited().orElse(false))));if (!policyDTO.isPresent()) {LOG.warn(@@ -179,48 +168,36 @@ public class MetadataObjectPolicyOperations {MetadataObjects.parse(fullName, MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));- Set<PolicyDTO> policies = Sets.newHashSet();- PolicyEntity[] nonInheritedPolicies =+ PolicyEntity[] policies =policyDispatcher.listPolicyInfosForMetadataObject(metalake, object);- nonInheritedPolicies =+ policies =MetadataAuthzHelper.filterByExpression(metalake,AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION,Entity.EntityType.POLICY,- nonInheritedPolicies,- (policyEntity -> NameIdentifierUtil.ofPolicy(metalake, policyEntity.name())));- if (ArrayUtils.isNotEmpty(nonInheritedPolicies)) {- Collections.addAll(- policies,- Arrays.stream(nonInheritedPolicies)- .map(t -> PolicyOperations.toDTO(t, Optional.of(false)))- .toArray(PolicyDTO[]::new));- }-- for (MetadataObject parentObject :- MetadataObjectUtil.getParentMetadataObjects(object)) {- PolicyEntity[] inheritedPolicies =- policyDispatcher.listPolicyInfosForMetadataObject(metalake, parentObject);- if (ArrayUtils.isNotEmpty(inheritedPolicies)) {- Collections.addAll(policies,- Arrays.stream(inheritedPolicies)- .map(t -> PolicyOperations.toDTO(t, Optional.of(true)))- .toArray(PolicyDTO[]::new));- }- }+ policy -> NameIdentifierUtil.ofPolicy(metalake, policy.name()));++ PolicyDTO[] policyDTOs =+ Arrays.stream(policies)+ .map(+ policy ->+ PolicyOperations.toDTO(+ policy, Optional.of(policy.inherited().orElse(false))))+ .toArray(PolicyDTO[]::new);if (verbose) {LOG.info("List {} policies info for object type: {}, full name: {} under metalake: {}",- policies.size(),+ policyDTOs.length,type,fullName,metalake);- return Utils.ok(new PolicyListResponse(policies.toArray(new PolicyDTO[0])));+ return Utils.ok(new PolicyListResponse(policyDTOs));} else {- String[] policyNames = policies.stream().map(PolicyDTO::name).toArray(String[]::new);+ String[] policyNames =+ Arrays.stream(policyDTOs).map(PolicyDTO::name).toArray(String[]::new);LOG.info("List {} policies for object type: {}, full name: {} under metalake: {}",@@ -237,6 +214,7 @@ public class MetadataObjectPolicyOperations {}}+ @Deprecated@POST@Produces("application/vnd.gravitino.v1+json")@Timed(name = "associate-object-policies." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectTagOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectTagOperations.javaindex 072f3876cc..66ac0fc8ab 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectTagOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectTagOperations.java@@ -94,7 +94,8 @@ public class MetadataObjectTagOperations {@Timed(name = "get-object-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "get-object-tag", absolute = true)@AuthorizationExpression(- expression = "METALAKE::OWNER || ((TAG::OWNER || ANY_APPLY_TAG) && CAN_ACCESS_METADATA)")+ expression =+ "METALAKE::OWNER || ((TAG::OWNER || ANY_VIEW_TAG || ANY_APPLY_TAG) && CAN_ACCESS_METADATA)")public Response getTagForObject(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.javaindex 1816356524..2f2305176b 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/PolicyOperations.java@@ -40,6 +40,8 @@ import javax.ws.rs.core.Context;import javax.ws.rs.core.Response;import org.apache.gravitino.Entity;import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.RelationalEntity;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;import org.apache.gravitino.dto.policy.PolicyDTO;import org.apache.gravitino.dto.requests.PolicyCreateRequest;import org.apache.gravitino.dto.requests.PolicySetRequest;@@ -51,10 +53,15 @@ import org.apache.gravitino.dto.responses.MetadataObjectListResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.PolicyListResponse;import org.apache.gravitino.dto.responses.PolicyResponse;+import org.apache.gravitino.dto.responses.TagForPolicyAssociationListResponse;import org.apache.gravitino.dto.tag.MetadataObjectDTO;+import org.apache.gravitino.dto.tag.TagForPolicyAssociationDTO;import org.apache.gravitino.dto.util.DTOConverters;+import org.apache.gravitino.json.PolicyAssociationSelectorSerde;import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.metrics.MetricNames;+import org.apache.gravitino.policy.AllValuesSelector;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyDispatcher;@@ -356,6 +363,59 @@ public class PolicyOperations {}}+ @GET+ @Path("{policy}/tags")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "list-tags-for-policy." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "list-tags-for-policy", absolute = true)+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION)+ public Response listTagsForPolicy(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("policy") @AuthorizationMetadata(type = Entity.EntityType.POLICY)+ String policyName,+ @QueryParam("details") @DefaultValue("false") boolean verbose) {+ LOG.info(+ "Received list tag associations for policy: {} under metalake: {}", policyName, metalake);+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ RelationalEntity<?>[] associations =+ policyDispatcher.listTagAssociationsForPolicy(metalake, policyName);+ associations =+ MetadataAuthzHelper.filterByExpression(+ metalake,+ AuthorizationExpressionConstants.LOAD_TAG_AUTHORIZATION_EXPRESSION,+ Entity.EntityType.TAG,+ associations,+ association ->+ NameIdentifierUtil.ofTag(metalake, association.targetEntity().name()));+ if (!verbose) {+ String[] names =+ Arrays.stream(associations)+ .map(association -> association.targetEntity().name())+ .toArray(String[]::new);+ return Utils.ok(new NameListResponse(names));+ }++ TagForPolicyAssociationDTO[] associationDTOs =+ Arrays.stream(associations)+ .map(+ association ->+ new TagForPolicyAssociationDTO(+ DTOConverters.toDTO(+ (TagEntity) association.targetEntity(), Optional.empty()),+ toSelectorDTO(association)))+ .toArray(TagForPolicyAssociationDTO[]::new);+ return Utils.ok(new TagForPolicyAssociationListResponse(associationDTOs));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handlePolicyException(OperationType.LIST, policyName, metalake, e);+ }+ }+static PolicyDTO toDTO(PolicyEntity policy, Optional<Boolean> inherited) {String policyType = policy.policyType().policyType();PolicyDTO.Builder builder =@@ -371,6 +431,14 @@ public class PolicyOperations {return builder.build();}+ static PolicyAssociationSelectorDTO toSelectorDTO(RelationalEntity<?> association) {+ return PolicyAssociationSelectorDTO.fromSelector(+ association+ .relationValue()+ .map(PolicyAssociationSelectorSerde::deserialize)+ .orElseGet(AllValuesSelector::get));+ }+private static void validateCreatePolicyType(String policyType) {Policy.BuiltInType builtInType = Policy.BuiltInType.fromPolicyType(policyType);if (builtInType != Policy.BuiltInType.CUSTOMdiff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.javaindex 8c0427a43e..eed4e13548 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java@@ -42,6 +42,10 @@ import org.apache.commons.lang3.ArrayUtils;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Entity;import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.RelationalEntity;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;+import org.apache.gravitino.dto.policy.PolicyForTagAssociationDTO;+import org.apache.gravitino.dto.requests.PolicyTagAddRequest;import org.apache.gravitino.dto.requests.TagCreateRequest;import org.apache.gravitino.dto.requests.TagUpdateRequest;import org.apache.gravitino.dto.requests.TagUpdatesRequest;@@ -49,11 +53,14 @@ import org.apache.gravitino.dto.requests.TagsAssociateRequest;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.MetadataObjectListResponse;import org.apache.gravitino.dto.responses.NameListResponse;+import org.apache.gravitino.dto.responses.PolicyForTagAssociationListResponse;+import org.apache.gravitino.dto.responses.PolicyTagAssociationResponse;import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;import org.apache.gravitino.dto.tag.MetadataObjectDTO;import org.apache.gravitino.dto.tag.TagDTO;import org.apache.gravitino.dto.util.DTOConverters;+import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;@@ -325,6 +332,125 @@ public class TagOperations {}}+ @GET+ @Path("{tag}/policies")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "list-policies-for-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "list-policies-for-tag", absolute = true)+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_TAG_AUTHORIZATION_EXPRESSION)+ public Response listPoliciesForTag(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("tag") @AuthorizationMetadata(type = Entity.EntityType.TAG) String tagName,+ @QueryParam("details") @DefaultValue("false") boolean verbose) {+ LOG.info("Received list policy associations for tag: {} under metalake: {}", tagName, metalake);+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ RelationalEntity<?>[] associations =+ tagDispatcher.listPolicyAssociationsForTag(metalake, tagName);+ associations =+ MetadataAuthzHelper.filterByExpression(+ metalake,+ AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION,+ Entity.EntityType.POLICY,+ associations,+ association ->+ NameIdentifierUtil.ofPolicy(metalake, association.targetEntity().name()));+ if (!verbose) {+ String[] names =+ Arrays.stream(associations)+ .map(association -> association.targetEntity().name())+ .toArray(String[]::new);+ return Utils.ok(new NameListResponse(names));+ }++ PolicyForTagAssociationDTO[] associationDTOs =+ Arrays.stream(associations)+ .map(+ association ->+ new PolicyForTagAssociationDTO(+ PolicyOperations.toDTO(+ (PolicyEntity) association.targetEntity(), Optional.empty()),+ PolicyOperations.toSelectorDTO(association)))+ .toArray(PolicyForTagAssociationDTO[]::new);+ return Utils.ok(new PolicyForTagAssociationListResponse(associationDTOs));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTagException(OperationType.LIST, tagName, metalake, e);+ }+ }++ @POST+ @Path("{tag}/policies/{policy}")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "add-policy-for-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "add-policy-for-tag", absolute = true)+ @AuthorizationExpression(+ expression =+ "METALAKE::OWNER || ((TAG::OWNER || ANY_APPLY_TAG) && (POLICY::OWNER || ANY_APPLY_POLICY))")+ public Response addPolicyForTag(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("tag") @AuthorizationMetadata(type = Entity.EntityType.TAG) String tagName,+ @PathParam("policy") @AuthorizationMetadata(type = Entity.EntityType.POLICY)+ String policyName,+ PolicyTagAddRequest request) {+ LOG.info(+ "Received add policy: {} for tag: {} under metalake: {}", policyName, tagName, metalake);+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ PolicyTagAddRequest effectiveRequest =+ request == null ? new PolicyTagAddRequest() : request;+ effectiveRequest.validate();+ tagDispatcher.addPolicyForTag(+ metalake, tagName, policyName, effectiveRequest.selector());+ return Utils.ok(+ new PolicyTagAssociationResponse(+ policyName,+ tagName,+ PolicyAssociationSelectorDTO.fromSelector(effectiveRequest.selector())));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTagException(OperationType.ASSOCIATE, tagName, metalake, e);+ }+ }++ @DELETE+ @Path("{tag}/policies/{policy}")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "remove-policy-from-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "remove-policy-from-tag", absolute = true)+ @AuthorizationExpression(+ expression =+ "METALAKE::OWNER || ((TAG::OWNER || ANY_APPLY_TAG) && (POLICY::OWNER || ANY_APPLY_POLICY))")+ public Response removePolicyFromTag(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("tag") @AuthorizationMetadata(type = Entity.EntityType.TAG) String tagName,+ @PathParam("policy") @AuthorizationMetadata(type = Entity.EntityType.POLICY)+ String policyName) {+ LOG.info(+ "Received remove policy: {} from tag: {} under metalake: {}",+ policyName,+ tagName,+ metalake);+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ tagDispatcher.removePolicyFromTag(metalake, tagName, policyName);+ return Response.noContent().build();+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleTagException(OperationType.REMOVE, tagName, metalake, e);+ }+ }+private static void validateTagAssignmentValueFilter(String value) {if (value == null) {return;@@ -374,7 +500,8 @@ public class TagOperations {@Timed(name = "get-object-tag." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "get-object-tag", absolute = true)@AuthorizationExpression(- expression = "METALAKE::OWNER || ((TAG::OWNER || ANY_APPLY_TAG) && CAN_ACCESS_METADATA)")+ expression =+ "METALAKE::OWNER || ((TAG::OWNER || ANY_VIEW_TAG || ANY_APPLY_TAG) && CAN_ACCESS_METADATA)")public Response getTagForObject(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.javaindex 6ff31e2203..f3d8d52dfb 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectPolicyOperations.java@@ -18,6 +18,8 @@*/package org.apache.gravitino.server.web.rest;+import static org.apache.gravitino.Configs.CACHE_ENABLED;+import static org.apache.gravitino.Configs.ENABLE_AUTHORIZATION;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;@@ -37,6 +39,9 @@ import javax.ws.rs.client.Entity;import javax.ws.rs.core.Application;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;+import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;import org.apache.gravitino.dto.requests.PoliciesAssociateRequest;@@ -55,11 +60,16 @@ import org.apache.gravitino.policy.PolicyContents;import org.apache.gravitino.policy.PolicyDispatcher;import org.apache.gravitino.policy.PolicyManager;import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;import org.glassfish.jersey.internal.inject.AbstractBinder;import org.glassfish.jersey.server.ResourceConfig;import org.glassfish.jersey.test.TestProperties;import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;+import org.mockito.Mockito;public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {@@ -82,6 +92,14 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {private final PolicyContent policyContent =PolicyContents.custom(null, ImmutableSet.of(MetadataObject.Type.TABLE), null);+ @BeforeAll+ public static void setup() throws IllegalAccessException {+ Config config = mock(Config.class);+ Mockito.doReturn(false).when(config).get(CACHE_ENABLED);+ Mockito.doReturn(false).when(config).get(ENABLE_AUTHORIZATION);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);+ }+@Overrideprotected Application configure() {try {@@ -116,11 +134,14 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {when(policyManager.listPolicyInfosForMetadataObject(metalake, catalog)).thenReturn(catalogPolicyInfos);- PolicyEntity[] schemaPolicyInfos = new PolicyEntity[] {createPolicy("policy3")};+ PolicyEntity[] schemaPolicyInfos =+ new PolicyEntity[] {createPolicy("policy1"), createPolicy("policy3")};when(policyManager.listPolicyInfosForMetadataObject(metalake, schema)).thenReturn(schemaPolicyInfos);- PolicyEntity[] tablePolicyInfos = {createPolicy("policy5")};+ PolicyEntity[] tablePolicyInfos = {+ createPolicy("policy1"), createPolicy("policy3"), createPolicy("policy5")+ };when(policyManager.listPolicyInfosForMetadataObject(metalake, table)).thenReturn(tablePolicyInfos);@@ -181,9 +202,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {PolicyListResponse policyListResponse1 = response2.readEntity(PolicyListResponse.class);Assertions.assertEquals(0, policyListResponse1.getCode());- Assertions.assertEquals(- schemaPolicyInfos.length + catalogPolicyInfos.length,- policyListResponse1.getPolicies().length);+ Assertions.assertEquals(schemaPolicyInfos.length, policyListResponse1.getPolicies().length);Map<String, Policy> resultPolicies1 =Arrays.stream(policyListResponse1.getPolicies())@@ -192,7 +211,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertTrue(resultPolicies1.containsKey("policy1"));Assertions.assertTrue(resultPolicies1.containsKey("policy3"));- Assertions.assertTrue(resultPolicies1.get("policy1").inherited().get());+ Assertions.assertFalse(resultPolicies1.get("policy1").inherited().get());Assertions.assertFalse(resultPolicies1.get("policy3").inherited().get());Response response3 =@@ -208,8 +227,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {NameListResponse nameListResponse1 = response3.readEntity(NameListResponse.class);Assertions.assertEquals(0, nameListResponse1.getCode());- Assertions.assertEquals(- schemaPolicyInfos.length + catalogPolicyInfos.length, nameListResponse1.getNames().length);+ Assertions.assertEquals(schemaPolicyInfos.length, nameListResponse1.getNames().length);Set<String> resultNames = Sets.newHashSet(nameListResponse1.getNames());Assertions.assertTrue(resultNames.contains("policy1"));Assertions.assertTrue(resultNames.contains("policy3"));@@ -229,9 +247,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {PolicyListResponse policyListResponse2 = response4.readEntity(PolicyListResponse.class);Assertions.assertEquals(0, policyListResponse2.getCode());- Assertions.assertEquals(- schemaPolicyInfos.length + catalogPolicyInfos.length + tablePolicyInfos.length,- policyListResponse2.getPolicies().length);+ Assertions.assertEquals(tablePolicyInfos.length, policyListResponse2.getPolicies().length);Map<String, Policy> resultPolicies2 =Arrays.stream(policyListResponse2.getPolicies())@@ -241,8 +257,8 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertTrue(resultPolicies2.containsKey("policy3"));Assertions.assertTrue(resultPolicies2.containsKey("policy5"));- Assertions.assertTrue(resultPolicies2.get("policy1").inherited().get());- Assertions.assertTrue(resultPolicies2.get("policy3").inherited().get());+ Assertions.assertFalse(resultPolicies2.get("policy1").inherited().get());+ Assertions.assertFalse(resultPolicies2.get("policy3").inherited().get());Assertions.assertFalse(resultPolicies2.get("policy5").inherited().get());Response response5 =@@ -258,9 +274,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {NameListResponse nameListResponse2 = response5.readEntity(NameListResponse.class);Assertions.assertEquals(0, nameListResponse2.getCode());- Assertions.assertEquals(- schemaPolicyInfos.length + catalogPolicyInfos.length + tablePolicyInfos.length,- nameListResponse2.getNames().length);+ Assertions.assertEquals(tablePolicyInfos.length, nameListResponse2.getNames().length);Set<String> resultNames1 = Sets.newHashSet(nameListResponse2.getNames());Assertions.assertTrue(resultNames1.contains("policy1"));@@ -312,27 +326,19 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {@Testpublic void testListPoliciesForObjectUnderHierarchicalSchema() {- // Hierarchical (multi-level) schema "a:b:c" using the default separator ":". Its ancestor- // schemas are "a" and "a:b". A table under it must inherit policies from the schema itself,- // all ancestor schemas, and the catalog. The REST operation resolves the separator via- // MetadataObjectUtil.getParentMetadataObjects(MetadataObject), which falls back to the default- // ":" here because GravitinoEnv config is not booted in this unit test.- MetadataObject catalog = MetadataObjects.parse("hcat", MetadataObject.Type.CATALOG);- MetadataObject schemaA = MetadataObjects.parse("hcat.a", MetadataObject.Type.SCHEMA);- MetadataObject schemaB = MetadataObjects.parse("hcat.a:b", MetadataObject.Type.SCHEMA);- MetadataObject schemaC = MetadataObjects.parse("hcat.a:b:c", MetadataObject.Type.SCHEMA);+ // The manager resolves effective tags across the complete hierarchy before returning policies.+ // The REST layer must consume that result without querying each ancestor again.MetadataObject table = MetadataObjects.parse("hcat.a:b:c.tbl", MetadataObject.Type.TABLE);- when(policyManager.listPolicyInfosForMetadataObject(metalake, catalog))- .thenReturn(new PolicyEntity[] {createPolicy("catalogPolicy")});- when(policyManager.listPolicyInfosForMetadataObject(metalake, schemaA))- .thenReturn(new PolicyEntity[] {createPolicy("schemaAPolicy")});- when(policyManager.listPolicyInfosForMetadataObject(metalake, schemaB))- .thenReturn(new PolicyEntity[] {createPolicy("schemaBPolicy")});- when(policyManager.listPolicyInfosForMetadataObject(metalake, schemaC))- .thenReturn(new PolicyEntity[] {createPolicy("schemaCPolicy")});when(policyManager.listPolicyInfosForMetadataObject(metalake, table))- .thenReturn(new PolicyEntity[] {createPolicy("tablePolicy")});+ .thenReturn(+ new PolicyEntity[] {+ createPolicy("tablePolicy"),+ createPolicy("schemaCPolicy").copyWithInherited(true),+ createPolicy("schemaBPolicy").copyWithInherited(true),+ createPolicy("schemaAPolicy").copyWithInherited(true),+ createPolicy("catalogPolicy").copyWithInherited(true)+ });Response response =target(basePath(metalake))@@ -362,22 +368,18 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {@Testpublic void testGetPolicyForObjectUnderHierarchicalSchema() {- // Hierarchical (multi-level) schema "a:b:c" using the default separator ":". The REST operation- // resolves the separator via MetadataObjectUtil.getParentMetadataObjects(MetadataObject), which- // falls back to the default ":" here because GravitinoEnv config is not booted in this unit- // test.- MetadataObject schemaA = MetadataObjects.parse("hcat.a", MetadataObject.Type.SCHEMA);- MetadataObject schemaB = MetadataObjects.parse("hcat.a:b", MetadataObject.Type.SCHEMA);+ // The manager resolves policies from the table's effective tags, including inherited tags.+ // The REST layer queries only the requested table.MetadataObject table = MetadataObjects.parse("hcat.a:b:c.tbl", MetadataObject.Type.TABLE);- PolicyEntity schemaAPolicy = createPolicy("schemaAPolicy");- PolicyEntity schemaBPolicy = createPolicy("schemaBPolicy");- when(policyManager.getPolicyForMetadataObject(metalake, schemaA, "schemaAPolicy"))+ PolicyEntity schemaAPolicy = createPolicy("schemaAPolicy").copyWithInherited(true);+ PolicyEntity schemaBPolicy = createPolicy("schemaBPolicy").copyWithInherited(true);+ when(policyManager.getPolicyForMetadataObject(metalake, table, schemaAPolicy.name())).thenReturn(schemaAPolicy);- when(policyManager.getPolicyForMetadataObject(metalake, schemaB, "schemaBPolicy"))+ when(policyManager.getPolicyForMetadataObject(metalake, table, schemaBPolicy.name())).thenReturn(schemaBPolicy);- // A policy on the intermediate schema "a:b" is inherited by a table under "a:b:c".+ // A policy selected by an inherited tag is resolved directly for the table.Response responseB =target(basePath(metalake)).path(table.type().toString())@@ -392,7 +394,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertEquals("schemaBPolicy", respPolicyB.name());Assertions.assertTrue(respPolicyB.inherited().get());- // A policy on the ancestor schema "a" is also inherited by a table under "a:b:c".+ // The same rule applies to a tag inherited from a more distant ancestor.Response responseA =target(basePath(metalake)).path(table.type().toString())@@ -408,6 +410,96 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertTrue(respPolicyA.inherited().get());}+ @Test+ public void testParentTagDerivedPolicyIsNotReturnedForChild() {+ MetadataObject schema = MetadataObjects.parse("catalog.schema", MetadataObject.Type.SCHEMA);+ MetadataObject table = MetadataObjects.parse("catalog.schema.table", MetadataObject.Type.TABLE);+ PolicyEntity parentDerivedPolicy = createPolicy("financePolicy");++ when(policyManager.listPolicyInfosForMetadataObject(metalake, table))+ .thenReturn(new PolicyEntity[0]);+ when(policyManager.listPolicyInfosForMetadataObject(metalake, schema))+ .thenReturn(new PolicyEntity[] {parentDerivedPolicy});+ when(policyManager.getPolicyForMetadataObject(metalake, table, parentDerivedPolicy.name()))+ .thenThrow(new NoSuchPolicyException("not applicable"));+ when(policyManager.getPolicyForMetadataObject(metalake, schema, parentDerivedPolicy.name()))+ .thenReturn(parentDerivedPolicy);++ Response listResponse =+ target(basePath(metalake))+ .path(table.type().toString())+ .path(table.fullName())+ .path("policies")+ .queryParam("details", true)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), listResponse.getStatus());+ Assertions.assertEquals(+ 0, listResponse.readEntity(PolicyListResponse.class).getPolicies().length);++ Response getResponse =+ target(basePath(metalake))+ .path(table.type().toString())+ .path(table.fullName())+ .path("policies")+ .path(parentDerivedPolicy.name())+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), getResponse.getStatus());++ Mockito.verify(policyManager, Mockito.never())+ .listPolicyInfosForMetadataObject(metalake, schema);+ Mockito.verify(policyManager, Mockito.never())+ .getPolicyForMetadataObject(metalake, schema, parentDerivedPolicy.name());+ }++ @Test+ public void testListPoliciesFiltersResolvedResult() throws IllegalAccessException {+ MetadataObject schema = MetadataObjects.parse("catalog.schema", MetadataObject.Type.SCHEMA);+ MetadataObject table = MetadataObjects.parse("catalog.schema.table", MetadataObject.Type.TABLE);+ PolicyEntity policy = createPolicy("hiddenPolicy");+ when(policyManager.listPolicyInfosForMetadataObject(metalake, table))+ .thenReturn(new PolicyEntity[] {policy});+ when(policyManager.listPolicyInfosForMetadataObject(metalake, schema))+ .thenReturn(new PolicyEntity[] {policy});++ MetadataObjectPolicyOperations operations = new MetadataObjectPolicyOperations(policyManager);+ HttpServletRequest request = mock(HttpServletRequest.class);+ FieldUtils.writeField(operations, "httpRequest", request, true);++ try (MockedStatic<MetadataAuthzHelper> metadataAuthzHelper =+ Mockito.mockStatic(MetadataAuthzHelper.class)) {+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.filterByExpression(+ Mockito.eq(metalake),+ Mockito.eq(+ AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION),+ Mockito.eq(org.apache.gravitino.Entity.EntityType.POLICY),+ Mockito.any(PolicyEntity[].class),+ Mockito.any()))+ .thenReturn(new PolicyEntity[0]);++ Response detailsResponse =+ operations.listPoliciesForMetadataObject(+ metalake, table.type().toString(), table.fullName(), true);+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), detailsResponse.getStatus());+ Assertions.assertEquals(+ 0, ((PolicyListResponse) detailsResponse.getEntity()).getPolicies().length);++ Response namesResponse =+ operations.listPoliciesForMetadataObject(+ metalake, table.type().toString(), table.fullName(), false);+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), namesResponse.getStatus());+ Assertions.assertEquals(0, ((NameListResponse) namesResponse.getEntity()).getNames().length);+ }+ Mockito.verify(policyManager, Mockito.never())+ .listPolicyInfosForMetadataObject(metalake, schema);+ }+@Testpublic void testGetPolicyForObject() {PolicyEntity policy1 = createPolicy("policy1");@@ -423,6 +515,10 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {MetadataObject table =MetadataObjects.parse("object1.object2.object3", MetadataObject.Type.TABLE);when(policyManager.getPolicyForMetadataObject(metalake, table, "policy3")).thenReturn(policy3);+ when(policyManager.getPolicyForMetadataObject(metalake, schema, "policy1"))+ .thenReturn(policy1.copyWithInherited(true));+ when(policyManager.getPolicyForMetadataObject(metalake, table, "policy2"))+ .thenReturn(policy2.copyWithInherited(true));// Test catalog policyResponse response =@@ -487,7 +583,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertEquals(policy3.comment(), respPolicy2.comment());Assertions.assertFalse(respPolicy2.inherited().get());- // Test get schema inherited policy+ // Test a schema policy resolved from an effective tagResponse response4 =target(basePath(metalake)).path(schema.type().toString())@@ -508,7 +604,7 @@ public class TestMetadataObjectPolicyOperations extends BaseOperationsTest {Assertions.assertEquals(policy1.comment(), respPolicy4.comment());Assertions.assertTrue(respPolicy4.inherited().get());- // Test get table inherited policy+ // Test a table policy resolved from an effective tagResponse response5 =target(basePath(metalake)).path(table.type().toString())diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.javaindex 85e45239fe..76c66e38fb 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java@@ -44,6 +44,9 @@ import org.apache.gravitino.Config;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.RelationalEntity;+import org.apache.gravitino.SupportsRelationOperations;import org.apache.gravitino.dto.policy.PolicyContentDTO;import org.apache.gravitino.dto.requests.PolicyCreateRequest;import org.apache.gravitino.dto.requests.PolicySetRequest;@@ -57,11 +60,14 @@ import org.apache.gravitino.dto.responses.MetadataObjectListResponse;import org.apache.gravitino.dto.responses.NameListResponse;import org.apache.gravitino.dto.responses.PolicyListResponse;import org.apache.gravitino.dto.responses.PolicyResponse;+import org.apache.gravitino.dto.responses.TagForPolicyAssociationListResponse;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.meta.TagEntity;+import org.apache.gravitino.policy.AllValuesSelector;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyChange;import org.apache.gravitino.policy.PolicyContent;@@ -199,6 +205,49 @@ public class TestPolicyOperations extends BaseOperationsTest {Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp1.getType());}+ @Test+ public void testTagAssociationsForPolicy() {+ String policyName = "policy1";+ String tagName = "tag1";+ TagEntity tag = mock(TagEntity.class);+ when(tag.name()).thenReturn(tagName);+ when(tag.properties()).thenReturn(ImmutableMap.of());+ when(tag.assignment()).thenReturn(Optional.empty());+ when(tag.auditInfo()).thenReturn(testAuditInfo1);+ RelationalEntity<TagEntity> association =+ new RelationalEntity<>(+ SupportsRelationOperations.Type.POLICY_TAG_REL,+ NameIdentifier.of(metalake, policyName),+ org.apache.gravitino.Entity.EntityType.POLICY,+ tag);+ when(policyManager.listTagAssociationsForPolicy(metalake, policyName))+ .thenReturn(new RelationalEntity<?>[] {association});++ Response response =+ target(policyPath(metalake) + "/" + policyName + "/tags")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());+ Assertions.assertArrayEquals(+ new String[] {tagName}, response.readEntity(NameListResponse.class).getNames());++ Response detailsResponse =+ target(policyPath(metalake) + "/" + policyName + "/tags")+ .queryParam("details", true)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), detailsResponse.getStatus());+ TagForPolicyAssociationListResponse details =+ detailsResponse.readEntity(TagForPolicyAssociationListResponse.class);+ details.validate();+ Assertions.assertEquals(1, details.getAssociations().length);+ Assertions.assertSame(+ AllValuesSelector.get(), details.getAssociations()[0].getSelector().toSelector());+ }+@Testpublic void testListPolicyInfos() {ImmutableMap<String, Object> contentFields = ImmutableMap.of("target_file_size_bytes", 1000);diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.javaindex c4672a1114..f98d6696fd 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java@@ -30,6 +30,7 @@ import com.google.common.collect.Sets;import java.io.IOException;import java.time.Instant;import java.util.Arrays;+import java.util.Collections;import java.util.Map;import java.util.Optional;import java.util.Set;@@ -45,6 +46,11 @@ import org.apache.gravitino.Config;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.RelationalEntity;+import org.apache.gravitino.SupportsRelationOperations;+import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;+import org.apache.gravitino.dto.requests.PolicyTagAddRequest;import org.apache.gravitino.dto.requests.TagCreateRequest;import org.apache.gravitino.dto.requests.TagUpdateRequest;import org.apache.gravitino.dto.requests.TagUpdatesRequest;@@ -54,14 +60,22 @@ import org.apache.gravitino.dto.responses.ErrorConstants;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.MetadataObjectListResponse;import org.apache.gravitino.dto.responses.NameListResponse;+import org.apache.gravitino.dto.responses.PolicyForTagAssociationListResponse;+import org.apache.gravitino.dto.responses.PolicyTagAssociationResponse;import org.apache.gravitino.dto.responses.TagListResponse;import org.apache.gravitino.dto.responses.TagResponse;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NoSuchTagException;+import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;import org.apache.gravitino.exceptions.TagAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.meta.TagEntity;+import org.apache.gravitino.policy.AllValuesSelector;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.policy.TagValueSelector;import org.apache.gravitino.rest.RESTUtils;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagChange;@@ -198,6 +212,107 @@ public class TestTagOperations extends BaseOperationsTest {Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp1.getType());}+ @Test+ public void testPolicyAssociationsForTag() {+ String tagName = "tag1";+ String policyName = "policy1";+ PolicyEntity policy = mock(PolicyEntity.class);+ when(policy.name()).thenReturn(policyName);+ when(policy.policyType()).thenReturn(Policy.BuiltInType.CUSTOM);+ when(policy.enabled()).thenReturn(true);+ when(policy.content())+ .thenReturn(+ PolicyContents.custom(+ Collections.emptyMap(), Collections.singleton(MetadataObject.Type.TABLE), null));+ when(policy.auditInfo()).thenReturn(testAuditInfo1);+ RelationalEntity<PolicyEntity> association =+ new RelationalEntity<>(+ SupportsRelationOperations.Type.POLICY_TAG_REL,+ NameIdentifier.of(metalake, tagName),+ org.apache.gravitino.Entity.EntityType.TAG,+ policy);+ when(tagManager.listPolicyAssociationsForTag(metalake, tagName))+ .thenReturn(new RelationalEntity<?>[] {association});++ Response listResponse =+ target(tagPath(metalake) + "/" + tagName + "/policies")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), listResponse.getStatus());+ Assertions.assertArrayEquals(+ new String[] {policyName}, listResponse.readEntity(NameListResponse.class).getNames());++ Response detailsResponse =+ target(tagPath(metalake) + "/" + tagName + "/policies")+ .queryParam("details", true)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .get();+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), detailsResponse.getStatus());+ PolicyForTagAssociationListResponse details =+ detailsResponse.readEntity(PolicyForTagAssociationListResponse.class);+ details.validate();+ Assertions.assertEquals(1, details.getAssociations().length);+ Assertions.assertSame(+ AllValuesSelector.get(), details.getAssociations()[0].getSelector().toSelector());++ PolicyAssociationSelectorDTO selector =+ PolicyAssociationSelectorDTO.fromSelector(AllValuesSelector.get());+ PolicyTagAddRequest request = new PolicyTagAddRequest(selector);+ Response addResponse =+ target(tagPath(metalake) + "/" + tagName + "/policies/" + policyName)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), addResponse.getStatus());+ PolicyTagAssociationResponse response =+ addResponse.readEntity(PolicyTagAssociationResponse.class);+ response.validate();+ Assertions.assertEquals(policyName, response.getPolicy());+ Assertions.assertEquals(tagName, response.getTag());+ Assertions.assertEquals(AllValuesSelector.get(), response.getSelector().toSelector());+ Mockito.verify(tagManager)+ .addPolicyForTag(metalake, tagName, policyName, AllValuesSelector.get());++ Response removeResponse =+ target(tagPath(metalake) + "/" + tagName + "/policies/" + policyName)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .delete();+ Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), removeResponse.getStatus());+ Mockito.verify(tagManager).removePolicyFromTag(metalake, tagName, policyName);+ }++ @Test+ public void testAddPolicyForTagAlreadyAssociated() {+ String tagName = "tag1";+ String policyName = "policy1";+ doThrow(new PolicyAlreadyAssociatedException("mock error"))+ .when(tagManager)+ .addPolicyForTag(+ Mockito.eq(metalake), Mockito.eq(tagName), Mockito.eq(policyName), Mockito.any());++ for (PolicyAssociationSelectorDTO selector :+ new PolicyAssociationSelectorDTO[] {+ PolicyAssociationSelectorDTO.fromSelector(AllValuesSelector.get()),+ PolicyAssociationSelectorDTO.fromSelector(TagValueSelector.of("finance"))+ }) {+ Response response =+ target(tagPath(metalake) + "/" + tagName + "/policies/" + policyName)+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .post(+ Entity.entity(+ new PolicyTagAddRequest(selector), MediaType.APPLICATION_JSON_TYPE));+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());+ ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResponse.getCode());+ Assertions.assertEquals(+ PolicyAlreadyAssociatedException.class.getSimpleName(), errorResponse.getType());+ }+ }+@Testpublic void testListTagsInfo() {TagEntity tag1 =diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java b/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.javanew file mode 100644index 0000000000..534f8ef933--- /dev/null+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/authorization/TestTagPolicyAuthorizationExpression.java@@ -0,0 +1,96 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.server.web.rest.authorization;++import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.APPLY_TAG_AUTHORIZATION_EXPRESSION;+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_POLICY_AUTHORIZATION_EXPRESSION;+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.LOAD_TAG_AUTHORIZATION_EXPRESSION;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.google.common.collect.ImmutableSet;+import java.lang.reflect.Method;+import ognl.OgnlException;+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;+import org.apache.gravitino.server.web.rest.MetadataObjectPolicyOperations;+import org.junit.jupiter.api.Test;++public class TestTagPolicyAuthorizationExpression {++ @Test+ public void testLoadTagWithViewOrApplyPrivilege() throws OgnlException {+ MockAuthorizationExpressionEvaluator evaluator =+ new MockAuthorizationExpressionEvaluator(LOAD_TAG_AUTHORIZATION_EXPRESSION);++ assertTrue(evaluator.getResult(ImmutableSet.of("TAG::VIEW_TAG")));+ assertTrue(evaluator.getResult(ImmutableSet.of("TAG::APPLY_TAG")));+ assertFalse(evaluator.getResult(ImmutableSet.of("TAG::VIEW_TAG", "TAG::DENY_VIEW_TAG")));+ assertFalse(evaluator.getResult(ImmutableSet.of("TAG::APPLY_TAG", "TAG::DENY_APPLY_TAG")));+ assertTrue(evaluator.getResult(ImmutableSet.of("TAG::APPLY_TAG", "TAG::DENY_VIEW_TAG")));+ assertTrue(evaluator.getResult(ImmutableSet.of("TAG::VIEW_TAG", "TAG::DENY_APPLY_TAG")));+ }++ @Test+ public void testViewTagDoesNotGrantApplyTag() throws OgnlException {+ MockAuthorizationExpressionEvaluator evaluator =+ new MockAuthorizationExpressionEvaluator(APPLY_TAG_AUTHORIZATION_EXPRESSION);++ assertFalse(evaluator.getResult(ImmutableSet.of("TAG::VIEW_TAG")));+ assertTrue(evaluator.getResult(ImmutableSet.of("TAG::APPLY_TAG")));+ }++ @Test+ public void testLoadPolicyWithViewOrApplyPrivilege() throws OgnlException {+ MockAuthorizationExpressionEvaluator evaluator =+ new MockAuthorizationExpressionEvaluator(LOAD_POLICY_AUTHORIZATION_EXPRESSION);++ assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::VIEW_POLICY")));+ assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY")));+ assertFalse(+ evaluator.getResult(ImmutableSet.of("POLICY::VIEW_POLICY", "POLICY::DENY_VIEW_POLICY")));+ assertFalse(+ evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY", "POLICY::DENY_APPLY_POLICY")));+ assertTrue(+ evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY", "POLICY::DENY_VIEW_POLICY")));+ assertTrue(+ evaluator.getResult(ImmutableSet.of("POLICY::VIEW_POLICY", "POLICY::DENY_APPLY_POLICY")));+ }++ @Test+ public void testGetMetadataObjectPolicyWithViewOrApplyPrivilege()+ throws ReflectiveOperationException, OgnlException {+ Method method =+ MetadataObjectPolicyOperations.class.getDeclaredMethod(+ "getPolicyForObject", String.class, String.class, String.class, String.class);+ assertFalse(method.isAnnotationPresent(Deprecated.class));++ AuthorizationExpression annotation = method.getAnnotation(AuthorizationExpression.class);+ MockAuthorizationExpressionEvaluator evaluator =+ new MockAuthorizationExpressionEvaluator(+ annotation.expression().replace("CAN_ACCESS_METADATA", "CATALOG::OWNER"));++ assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::VIEW_POLICY", "CATALOG::OWNER")));+ assertTrue(evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY", "CATALOG::OWNER")));+ assertFalse(+ evaluator.getResult(+ ImmutableSet.of(+ "POLICY::APPLY_POLICY", "POLICY::DENY_APPLY_POLICY", "CATALOG::OWNER")));+ assertFalse(evaluator.getResult(ImmutableSet.of("POLICY::APPLY_POLICY")));+ }+}