Skip to content

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

[#13907] feat(auth): Enforce authority for access-tag assignments (#15035)

Mehakmeet Singh606c06098bfc
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
index b5a0c99172..642cd0f7c2 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
@@ -60,8 +60,10 @@ import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;
@@ -77,6 +79,7 @@ import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.tag.TagAssignment;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
@@ -593,9 +596,22 @@ public class TagMetaService {
: observedEndpoint.namespaceIds()[0];
LiveEndpointService.lockLiveEndpoint(
metalakeIdent, Entity.EntityType.METALAKE, new NamespacedEntityId(metalakeId));
+ for (Map.Entry<NameIdentifier, Optional<NamespacedEntityId>> ancestor :
+ TagAssignmentAuthorization.checkedSchemaAncestors().entrySet()) {
+ if (ancestor.getValue().isPresent()) {
+ try {
+ LiveEndpointService.lockLiveEndpoint(
+ ancestor.getKey(), Entity.EntityType.SCHEMA, ancestor.getValue().get());
+ } catch (NoSuchEntityException changed) {
+ throw ExceptionUtils.concurrentModification(
+ Entity.EntityType.SCHEMA, ancestor.getKey());
+ }
+ }
+ }
if (objectType != Entity.EntityType.POLICY) {
LiveEndpointService.lockLiveEndpoint(objectIdent, objectType, observedEndpoint);
}
+ TagAssignmentAuthorization.checkTarget(objectIdent, objectType, observedEndpoint);
List<String> tagNamesToUpdate = tagNamesToUpdate(tagValuesToAdd, tagValuesToRemove);
List<TagPO> tagPOsToUpdate =
@@ -603,6 +619,7 @@ public class TagMetaService {
? Collections.emptyList()
: getTagPOsByMetalakeAndNames(metalake, tagNamesToUpdate);
tagPOsToUpdate = lockTagsForAssignment(tagPOsToUpdate);
+ checkAuthorizedTagClassification(metalake, tagNamesToUpdate, tagPOsToUpdate);
if (objectType == Entity.EntityType.POLICY) {
LiveEndpointService.lockLiveEndpoint(objectIdent, objectType, observedEndpoint);
}
@@ -1189,6 +1206,38 @@ public class TagMetaService {
});
}
+ private void checkAuthorizedTagClassification(
+ String metalake, List<String> requestedTags, List<TagPO> tags) {
+ Map<String, TagPO> currentTags = tagPOsByName(tags);
+ for (String name : requestedTags) {
+ NameIdentifier identifier = NameIdentifierUtil.ofTag(metalake, name);
+ Long checkedId = TagAssignmentAuthorization.checkedIdentity(identifier);
+ TagPO current = currentTags.get(name);
+ if (current == null && checkedId != null) {
+ current = currentTags.get(TagAssignmentAuthorization.checkedTagName(identifier));
+ }
+ if (checkedId != null && (current == null || !checkedId.equals(current.getTagId()))) {
+ throw ExceptionUtils.concurrentModification(Entity.EntityType.TAG, identifier);
+ }
+ }
+ List<NameIdentifier> descriptive =
+ tags.stream()
+ .map(tag -> NameIdentifierUtil.ofTag(metalake, tag.getTagName()))
+ .filter(TagAssignmentAuthorization::requiresDescriptive)
+ .collect(Collectors.toList());
+ if (descriptive.isEmpty()) {
+ return;
+ }
+ SessionUtils.clearSessionCache();
+ for (RelationalEntity<?> relation :
+ PolicyTagRelService.getInstance().listRelations(descriptive, Entity.EntityType.TAG)) {
+ if (((PolicyEntity) relation.targetEntity()).policyType()
+ == Policy.BuiltInType.ACCESS_CONTROL) {
+ throw ExceptionUtils.concurrentModification(Entity.EntityType.TAG, relation.source());
+ }
+ }
+ }
+
private List<GenericEntity> metadataObjectsForRelations(
List<? extends TagMetadataObjectRelPO> tagMetadataObjectRelPOs) {
List<GenericEntity> metadataObjects = Lists.newArrayList();
diff --git a/core/src/main/java/org/apache/gravitino/tag/TagAssignmentAuthorization.java b/core/src/main/java/org/apache/gravitino/tag/TagAssignmentAuthorization.java
new file mode 100644
index 0000000000..970cd170f2
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/tag/TagAssignmentAuthorization.java
@@ -0,0 +1,346 @@
+/*
+ * 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.tag;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Carries identities and tag classifications checked by a synchronous assignment request. */
+public final class TagAssignmentAuthorization implements AutoCloseable {
+ private static final ThreadLocal<TagAssignmentAuthorization> CURRENT = new ThreadLocal<>();
+
+ @Nullable private final TagAssignmentAuthorization previous;
+ private final Set<NameIdentifier> descriptiveTags = new HashSet<>();
+ private final Map<NameIdentifier, Long> checkedTags = new HashMap<>();
+ private final Map<NameIdentifier, String> checkedTagNames = new HashMap<>();
+ private final Map<NameIdentifier, Optional<NamespacedEntityId>> schemaAncestors =
+ new LinkedHashMap<>();
+ private boolean targetChecked;
+ private boolean targetAbsent;
+ @Nullable private NameIdentifier targetIdentifier;
+ @Nullable private Entity.EntityType targetType;
+ @Nullable private long[] targetIds;
+
+ private TagAssignmentAuthorization(@Nullable TagAssignmentAuthorization previous) {
+ this.previous = previous;
+ }
+
+ /**
+ * Opens a request scope.
+ *
+ * @return the new scope
+ */
+ public static TagAssignmentAuthorization open() {
+ TagAssignmentAuthorization scope = new TagAssignmentAuthorization(CURRENT.get());
+ CURRENT.set(scope);
+ return scope;
+ }
+
+ /**
+ * Returns whether a request scope is active on the current thread.
+ *
+ * @return whether a scope is active
+ */
+ public static boolean isActive() {
+ return CURRENT.get() != null;
+ }
+
+ /**
+ * Records the tag identity observed by authorization.
+ *
+ * @param tag the tag identifier
+ * @param id the observed stable tag ID
+ */
+ public static void recordIdentity(NameIdentifier tag, long id) {
+ recordIdentity(tag, id, tag.name());
+ }
+
+ /**
+ * Records the stored spelling of a tag along with its observed identity.
+ *
+ * @param tag the requested tag identifier
+ * @param id the observed stable tag ID
+ * @param storedName the name returned by the store
+ */
+ public static void recordIdentity(NameIdentifier tag, long id, String storedName) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null) {
+ scope.checkedTags.putIfAbsent(tag, id);
+ scope.checkedTagNames.putIfAbsent(tag, storedName);
+ }
+ }
+
+ /**
+ * Returns the stored spelling observed for a requested tag.
+ *
+ * @param tag the requested tag identifier
+ * @return the stored spelling, or null if none was recorded
+ */
+ @Nullable
+ public static String checkedTagName(NameIdentifier tag) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ return scope == null ? null : scope.checkedTagNames.get(tag);
+ }
+
+ /**
+ * Returns the tag ID observed by authorization, or null when none was recorded.
+ *
+ * @param tag the tag identifier
+ * @return the observed ID, or null
+ */
+ @Nullable
+ public static Long checkedIdentity(NameIdentifier tag) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ return scope == null ? null : scope.checkedTags.get(tag);
+ }
+
+ /**
+ * Records the target identity observed before authorization.
+ *
+ * @param identifier the normalized target identifier
+ * @param type the target type
+ * @param target the observed identity, or null if the target was absent
+ */
+ public static void recordTarget(
+ NameIdentifier identifier, Entity.EntityType type, @Nullable NamespacedEntityId target) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null) {
+ scope.targetChecked = true;
+ scope.targetAbsent = target == null;
+ scope.targetIdentifier = identifier;
+ scope.targetType = type;
+ scope.targetIds = target == null ? null : target.fullIds();
+ }
+ }
+
+ /**
+ * Records the closest existing ancestor when the target was not yet materialized.
+ *
+ * @param ancestor the observed ancestor identity
+ */
+ public static void recordMissingTargetAncestor(NamespacedEntityId ancestor) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null && scope.targetChecked && scope.targetAbsent && scope.targetIds == null) {
+ scope.targetIds = ancestor.fullIds();
+ }
+ }
+
+ /**
+ * Records a schema ancestor in outermost-first order.
+ *
+ * @param identifier the normalized schema identifier
+ * @param ancestor the observed identity, or null when absent
+ */
+ public static void recordSchemaAncestor(
+ NameIdentifier identifier, @Nullable NamespacedEntityId ancestor) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null) {
+ scope.schemaAncestors.putIfAbsent(identifier, Optional.ofNullable(ancestor));
+ }
+ }
+
+ /**
+ * Returns the schema ancestors recorded for the current request in lock order.
+ *
+ * @return the recorded ancestors
+ */
+ public static Map<NameIdentifier, Optional<NamespacedEntityId>> checkedSchemaAncestors() {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ return scope == null
+ ? Collections.emptyMap()
+ : Collections.unmodifiableMap(new LinkedHashMap<>(scope.schemaAncestors));
+ }
+
+ /**
+ * Returns the observed ID for the request's target or an authorization ancestor, when it exists.
+ *
+ * @param identifier the metadata identifier being authorized
+ * @param type the metadata type being authorized
+ * @return the observed ID, or null when the scope has no matching identity
+ */
+ @Nullable
+ public static Long checkedTargetIdentity(NameIdentifier identifier, MetadataObject.Type type) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope == null
+ || !scope.targetChecked
+ || scope.targetType == null
+ || scope.targetIdentifier == null) {
+ return null;
+ }
+ if (type == MetadataObject.Type.SCHEMA && scope.schemaAncestors.containsKey(identifier)) {
+ return scope.schemaAncestors.get(identifier).map(NamespacedEntityId::entityId).orElse(null);
+ }
+ if (scope.targetIds == null) {
+ return null;
+ }
+ int index = checkedPathIndex(scope, identifier, type);
+ return index >= 0 && index < scope.targetIds.length ? scope.targetIds[index] : null;
+ }
+
+ /**
+ * Returns whether a relevant target or ancestor was absent at authorization.
+ *
+ * @param identifier the metadata identifier being authorized
+ * @param type the metadata type being authorized
+ * @return whether the matching target or ancestor was absent
+ */
+ public static boolean wasCheckedAbsent(NameIdentifier identifier, MetadataObject.Type type) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null
+ && type == MetadataObject.Type.SCHEMA
+ && scope.schemaAncestors.containsKey(identifier)) {
+ return scope.schemaAncestors.get(identifier).isEmpty();
+ }
+ if (scope == null
+ || !scope.targetChecked
+ || !scope.targetAbsent
+ || scope.targetIdentifier == null) {
+ return false;
+ }
+ int index = checkedPathIndex(scope, identifier, type);
+ return index >= 0 && (scope.targetIds == null || index >= scope.targetIds.length);
+ }
+
+ /**
+ * Returns whether this metadata type can represent the checked target or an ancestor.
+ *
+ * @param type the metadata type being authorized
+ * @return whether the type can be relevant to the checked target
+ */
+ public static boolean hasTargetType(MetadataObject.Type type) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ return scope != null
+ && scope.targetChecked
+ && scope.targetType != null
+ && (scope.targetType.name().equals(type.name())
+ || type == MetadataObject.Type.METALAKE
+ || type == MetadataObject.Type.CATALOG
+ || type == MetadataObject.Type.SCHEMA
+ || type == MetadataObject.Type.TABLE);
+ }
+
+ /**
+ * Rejects a write if the target or an ancestor has changed identity.
+ *
+ * @param identifier the target identifier
+ * @param type the target type
+ * @param current the target identity used for the write
+ */
+ public static void checkTarget(
+ NameIdentifier identifier, Entity.EntityType type, NamespacedEntityId current) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null
+ && scope.targetChecked
+ && (scope.targetType != type
+ || !identifier.equals(scope.targetIdentifier)
+ || (scope.targetAbsent
+ ? scope.targetIds == null
+ || current.fullIds().length <= scope.targetIds.length
+ || !Arrays.equals(
+ scope.targetIds, Arrays.copyOf(current.fullIds(), scope.targetIds.length))
+ : !Arrays.equals(scope.targetIds, current.fullIds())))) {
+ throw new OptimisticLockException(
+ "The %s %s changed after authorization; retry the operation", type, identifier);
+ }
+ }
+
+ /**
+ * Records a tag whose assignment used descriptive-tag authorization.
+ *
+ * @param tag the tag identifier
+ */
+ public static void requireDescriptive(NameIdentifier tag) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ if (scope != null) {
+ scope.descriptiveTags.add(tag);
+ }
+ }
+
+ /**
+ * Returns whether the named tag must remain descriptive at mutation.
+ *
+ * @param tag the tag identifier
+ * @return whether the condition applies
+ */
+ public static boolean requiresDescriptive(NameIdentifier tag) {
+ TagAssignmentAuthorization scope = CURRENT.get();
+ return scope != null && scope.descriptiveTags.contains(tag);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void close() {
+ if (previous == null) {
+ CURRENT.remove();
+ } else {
+ CURRENT.set(previous);
+ }
+ }
+
+ private static int checkedPathIndex(
+ TagAssignmentAuthorization scope, NameIdentifier identifier, MetadataObject.Type type) {
+ if (scope.targetType.name().equals(type.name()) && identifier.equals(scope.targetIdentifier)) {
+ if (!scope.targetAbsent && scope.targetIds != null) {
+ return scope.targetIds.length - 1;
+ }
+ switch (type) {
+ case CATALOG:
+ return 1;
+ case SCHEMA:
+ return 2;
+ case COLUMN:
+ return 4;
+ default:
+ return 3;
+ }
+ }
+ if (type == MetadataObject.Type.METALAKE
+ && identifier.equals(NameIdentifier.of(scope.targetIdentifier.namespace().level(0)))) {
+ return 0;
+ }
+ if (type == MetadataObject.Type.CATALOG
+ && identifier.equals(NameIdentifierUtil.getCatalogIdentifier(scope.targetIdentifier))) {
+ return 1;
+ }
+ if (type == MetadataObject.Type.SCHEMA
+ && scope.targetIdentifier.namespace().length() > 1
+ && identifier.equals(NameIdentifierUtil.getSchemaIdentifier(scope.targetIdentifier))) {
+ return 2;
+ }
+ if (type == MetadataObject.Type.TABLE
+ && scope.targetType == Entity.EntityType.COLUMN
+ && identifier.equals(NameIdentifierUtil.getTableIdentifier(scope.targetIdentifier))) {
+ return 3;
+ }
+ return -1;
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
index d52b3afd7b..9b16109eb8 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
@@ -57,6 +57,7 @@ import org.apache.gravitino.RelationUpdate;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.authorization.Privileges;
import org.apache.gravitino.authorization.SecurableObjects;
import org.apache.gravitino.exceptions.NoSuchEntityException;
@@ -67,6 +68,7 @@ import org.apache.gravitino.meta.ColumnEntity;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.RoleEntity;
import org.apache.gravitino.meta.SchemaEntity;
@@ -74,6 +76,7 @@ import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.storage.RandomIdGenerator;
@@ -87,6 +90,7 @@ import org.apache.gravitino.storage.relational.po.TagPO;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.tag.TagValueConstraint;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -101,6 +105,123 @@ public class TestTagMetaService extends TestJDBCBackend {
private final Map<String, String> props = ImmutableMap.of("k1", "v1");
+ /** Verifies a changed schema identity rejects an assignment before writing relations. */
+ @TestTemplate
+ public void testAssignmentChecksSchemaIdentity() throws IOException {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog");
+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, "catalog", "schema");
+ TableEntity table =
+ createAndInsertTableEntity(Namespace.of(METALAKE_NAME, "catalog", "schema"), "table");
+ TagEntity tag = createAndInsertTagEntity("label", "", METALAKE_NAME);
+ TagMetaService service = TagMetaService.getInstance();
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordSchemaAncestor(
+ schema.nameIdentifier(),
+ new NamespacedEntityId(RandomIdGenerator.INSTANCE.nextId(), metalake.id(), catalog.id()));
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ service.associateTagsWithMetadataObject(
+ table.nameIdentifier(),
+ Entity.EntityType.TABLE,
+ new NameIdentifier[] {tag.nameIdentifier()},
+ new NameIdentifier[0]));
+ }
+ Assertions.assertTrue(
+ service
+ .listTagsForMetadataObject(table.nameIdentifier(), Entity.EntityType.TABLE)
+ .isEmpty());
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordSchemaAncestor(
+ schema.nameIdentifier(),
+ new NamespacedEntityId(schema.id(), metalake.id(), catalog.id()));
+ service.associateTagsWithMetadataObject(
+ table.nameIdentifier(),
+ Entity.EntityType.TABLE,
+ new NameIdentifier[] {tag.nameIdentifier()},
+ new NameIdentifier[0]);
+ }
+ Assertions.assertEquals(
+ 1,
+ service.listTagsForMetadataObject(table.nameIdentifier(), Entity.EntityType.TABLE).size());
+ }
+
+ /** Verifies that stale tag and target observations reject the assignment transaction. */
+ @TestTemplate
+ public void testAssignmentRechecksTagAndTarget() throws IOException {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog");
+ TagEntity tag = createAndInsertTagEntity("label", "", METALAKE_NAME);
+ TagMetaService service = TagMetaService.getInstance();
+ NameIdentifier[] added = {tag.nameIdentifier()};
+ NameIdentifier[] removed = {};
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(
+ catalog.nameIdentifier(),
+ catalog.type(),
+ new NamespacedEntityId(RandomIdGenerator.INSTANCE.nextId(), metalake.id()));
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ service.associateTagsWithMetadataObject(
+ catalog.nameIdentifier(), catalog.type(), added, removed));
+ }
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordIdentity(
+ tag.nameIdentifier(), RandomIdGenerator.INSTANCE.nextId());
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ service.associateTagsWithMetadataObject(
+ catalog.nameIdentifier(), catalog.type(), added, removed));
+ }
+ PolicyEntity policy =
+ PolicyEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withNamespace(Namespace.of(METALAKE_NAME))
+ .withName("access")
+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+ .withEnabled(false)
+ .withContent(
+ PolicyContents.accessControl(
+ List.of(Privilege.Name.SELECT_TABLE), List.of("reader")))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ backend.insert(policy, false);
+ backend.updateEntityRelations(
+ RelationUpdate.of(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ tag.nameIdentifier(),
+ Entity.EntityType.TAG,
+ new RelationEdgeTarget[] {
+ RelationEdgeTarget.of(policy.nameIdentifier(), Entity.EntityType.POLICY, null)
+ },
+ new RelationEdgeTarget[0]));
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordIdentity(tag.nameIdentifier(), tag.id());
+ TagAssignmentAuthorization.requireDescriptive(tag.nameIdentifier());
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ service.associateTagsWithMetadataObject(
+ catalog.nameIdentifier(), catalog.type(), added, removed));
+ }
+ Assertions.assertTrue(
+ service.listTagsForMetadataObject(catalog.nameIdentifier(), catalog.type()).isEmpty());
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordIdentity(tag.nameIdentifier(), tag.id());
+ TagAssignmentAuthorization.recordTarget(
+ catalog.nameIdentifier(),
+ catalog.type(),
+ new NamespacedEntityId(catalog.id(), metalake.id()));
+ service.associateTagsWithMetadataObject(
+ catalog.nameIdentifier(), catalog.type(), added, removed);
+ }
+ Assertions.assertEquals(
+ 1, service.listTagsForMetadataObject(catalog.nameIdentifier(), catalog.type()).size());
+ }
+
/** Verifies membership lookups against live stored tags and object lifecycles. */
@TestTemplate
public void testMetadataObjectLookupByStableTagId() throws IOException {
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagAssignmentAuthorization.java b/core/src/test/java/org/apache/gravitino/tag/TestTagAssignmentAuthorization.java
new file mode 100644
index 0000000000..15ed6693cb
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagAssignmentAuthorization.java
@@ -0,0 +1,181 @@
+/*
+ * 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.tag;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.junit.jupiter.api.Test;
+
+class TestTagAssignmentAuthorization {
+ @Test
+ void testScopeAndNestedScope() {
+ NameIdentifier tag = NameIdentifier.of("metalake", "tag");
+ NameIdentifier other = NameIdentifier.of("metalake", "other");
+ TagAssignmentAuthorization.requireDescriptive(tag);
+ TagAssignmentAuthorization.recordIdentity(tag, 1L);
+ assertFalse(TagAssignmentAuthorization.isActive());
+ assertNull(TagAssignmentAuthorization.checkedIdentity(tag));
+ assertFalse(TagAssignmentAuthorization.requiresDescriptive(tag));
+ try (TagAssignmentAuthorization outer = TagAssignmentAuthorization.open()) {
+ assertTrue(TagAssignmentAuthorization.isActive());
+ TagAssignmentAuthorization.recordIdentity(tag, 1L);
+ TagAssignmentAuthorization.recordIdentity(tag, 2L);
+ assertEquals(1L, TagAssignmentAuthorization.checkedIdentity(tag));
+ TagAssignmentAuthorization.requireDescriptive(tag);
+ assertTrue(TagAssignmentAuthorization.requiresDescriptive(tag));
+ assertFalse(TagAssignmentAuthorization.requiresDescriptive(other));
+ try (TagAssignmentAuthorization inner = TagAssignmentAuthorization.open()) {
+ assertNull(TagAssignmentAuthorization.checkedIdentity(tag));
+ assertFalse(TagAssignmentAuthorization.requiresDescriptive(tag));
+ TagAssignmentAuthorization.requireDescriptive(other);
+ assertTrue(TagAssignmentAuthorization.requiresDescriptive(other));
+ }
+ assertTrue(TagAssignmentAuthorization.requiresDescriptive(tag));
+ assertEquals(1L, TagAssignmentAuthorization.checkedIdentity(tag));
+ assertFalse(TagAssignmentAuthorization.requiresDescriptive(other));
+ }
+ assertFalse(TagAssignmentAuthorization.requiresDescriptive(tag));
+ assertFalse(TagAssignmentAuthorization.isActive());
+ assertNull(TagAssignmentAuthorization.checkedIdentity(tag));
+ }
+
+ @Test
+ void testTargetAndAncestorIdentity() {
+ NameIdentifier catalog = NameIdentifier.of("metalake", "catalog");
+ NamespacedEntityId original = new NamespacedEntityId(2L, 1L);
+ NamespacedEntityId replacement = new NamespacedEntityId(3L, 1L);
+ NamespacedEntityId changedAncestor = new NamespacedEntityId(2L, 4L);
+ assertDoesNotThrow(
+ () ->
+ TagAssignmentAuthorization.checkTarget(
+ catalog, Entity.EntityType.CATALOG, replacement));
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(catalog, Entity.EntityType.CATALOG, original);
+ assertTrue(TagAssignmentAuthorization.hasTargetType(MetadataObject.Type.CATALOG));
+ assertTrue(TagAssignmentAuthorization.hasTargetType(MetadataObject.Type.TABLE));
+ assertEquals(
+ 2L,
+ TagAssignmentAuthorization.checkedTargetIdentity(catalog, MetadataObject.Type.CATALOG));
+ assertNull(
+ TagAssignmentAuthorization.checkedTargetIdentity(
+ NameIdentifier.of("metalake", "other"), MetadataObject.Type.CATALOG));
+ assertDoesNotThrow(
+ () ->
+ TagAssignmentAuthorization.checkTarget(catalog, Entity.EntityType.CATALOG, original));
+ assertThrows(
+ OptimisticLockException.class,
+ () ->
+ TagAssignmentAuthorization.checkTarget(
+ catalog, Entity.EntityType.CATALOG, replacement));
+ assertThrows(
+ OptimisticLockException.class,
+ () ->
+ TagAssignmentAuthorization.checkTarget(
+ catalog, Entity.EntityType.CATALOG, changedAncestor));
+ assertThrows(
+ OptimisticLockException.class,
+ () -> TagAssignmentAuthorization.checkTarget(catalog, Entity.EntityType.TABLE, original));
+ TagAssignmentAuthorization.recordTarget(catalog, Entity.EntityType.CATALOG, null);
+ assertNull(
+ TagAssignmentAuthorization.checkedTargetIdentity(catalog, MetadataObject.Type.CATALOG));
+ assertThrows(
+ OptimisticLockException.class,
+ () ->
+ TagAssignmentAuthorization.checkTarget(catalog, Entity.EntityType.CATALOG, original));
+ assertTrue(TagAssignmentAuthorization.wasCheckedAbsent(catalog, MetadataObject.Type.CATALOG));
+ TagAssignmentAuthorization.recordMissingTargetAncestor(new NamespacedEntityId(1L));
+ assertEquals(
+ 1L,
+ TagAssignmentAuthorization.checkedTargetIdentity(
+ NameIdentifier.of("metalake"), MetadataObject.Type.METALAKE));
+ assertFalse(
+ TagAssignmentAuthorization.wasCheckedAbsent(
+ NameIdentifier.of("metalake"), MetadataObject.Type.METALAKE));
+ assertDoesNotThrow(
+ () ->
+ TagAssignmentAuthorization.checkTarget(catalog, Entity.EntityType.CATALOG, original));
+ assertThrows(
+ OptimisticLockException.class,
+ () ->
+ TagAssignmentAuthorization.checkTarget(
+ catalog, Entity.EntityType.CATALOG, changedAncestor));
+ NameIdentifier table = NameIdentifier.of("metalake", "catalog", "schema", "table");
+ TagAssignmentAuthorization.recordTarget(
+ table, Entity.EntityType.TABLE, new NamespacedEntityId(4L, 1L, 2L, 3L));
+ assertEquals(
+ 1L,
+ TagAssignmentAuthorization.checkedTargetIdentity(
+ NameIdentifier.of("metalake"), MetadataObject.Type.METALAKE));
+ assertEquals(
+ 2L,
+ TagAssignmentAuthorization.checkedTargetIdentity(catalog, MetadataObject.Type.CATALOG));
+ assertEquals(
+ 3L,
+ TagAssignmentAuthorization.checkedTargetIdentity(
+ NameIdentifier.of("metalake", "catalog", "schema"), MetadataObject.Type.SCHEMA));
+ assertNull(
+ TagAssignmentAuthorization.checkedTargetIdentity(
+ NameIdentifier.of("metalake", "other"), MetadataObject.Type.CATALOG));
+ }
+ assertDoesNotThrow(
+ () ->
+ TagAssignmentAuthorization.checkTarget(
+ catalog, Entity.EntityType.CATALOG, replacement));
+ }
+
+ @Test
+ void testSchemaAncestorSnapshots() {
+ NameIdentifier target = NameIdentifier.of("metalake", "catalog", "outer:inner", "table");
+ NameIdentifier outer = NameIdentifier.of("metalake", "catalog", "outer");
+ NameIdentifier inner = NameIdentifier.of("metalake", "catalog", "outer:inner");
+ TagAssignmentAuthorization.recordSchemaAncestor(outer, new NamespacedEntityId(3L, 1L, 2L));
+ assertTrue(TagAssignmentAuthorization.checkedSchemaAncestors().isEmpty());
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(target, Entity.EntityType.TABLE, null);
+ TagAssignmentAuthorization.recordSchemaAncestor(outer, new NamespacedEntityId(3L, 1L, 2L));
+ TagAssignmentAuthorization.recordSchemaAncestor(inner, null);
+ assertEquals(
+ List.of(outer, inner),
+ new ArrayList<>(TagAssignmentAuthorization.checkedSchemaAncestors().keySet()));
+ assertEquals(
+ 3L, TagAssignmentAuthorization.checkedTargetIdentity(outer, MetadataObject.Type.SCHEMA));
+ assertFalse(TagAssignmentAuthorization.wasCheckedAbsent(outer, MetadataObject.Type.SCHEMA));
+ assertTrue(TagAssignmentAuthorization.wasCheckedAbsent(inner, MetadataObject.Type.SCHEMA));
+ try (TagAssignmentAuthorization nested = TagAssignmentAuthorization.open()) {
+ assertTrue(TagAssignmentAuthorization.checkedSchemaAncestors().isEmpty());
+ }
+ assertEquals(
+ List.of(outer, inner),
+ new ArrayList<>(TagAssignmentAuthorization.checkedSchemaAncestors().keySet()));
+ }
+ assertTrue(TagAssignmentAuthorization.checkedSchemaAncestors().isEmpty());
+ }
+}
diff --git a/docs/security/access-control.md b/docs/security/access-control.md
index e4ec0d7da2..5fb2583d75 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -252,8 +252,13 @@ policy with tags, provided they also have `APPLY_TAG` on each tag. Granting it o
covers any policy in that metalake.
Assigning a tag to a metadata object requires `APPLY_TAG` on the tag and access to the object.
+For a tag bound to an access-control policy, adding or removing the tag instead requires an explicit
+`APPLY_TAG` grant on that tag and ownership or `MANAGE_GRANTS` on the object or an ancestor.
+Tag ownership or a metalake-level `APPLY_TAG` grant alone is not sufficient. The metalake owner
+can still assign or remove the tag.
Associating a policy with a tag requires access to both: `APPLY_POLICY` on the policy and
-`APPLY_TAG` on the tag. Ownership can satisfy either check.
+`APPLY_TAG` on the tag. For descriptive tags and policy association, ownership can satisfy the
+corresponding check.
Reading a tag requires `VIEW_TAG` or `APPLY_TAG`; reading a policy requires `VIEW_POLICY` or
`APPLY_POLICY`. The view privileges do not allow tag assignment or policy-to-tag association.
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/AuthorizationRequestScope.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/AuthorizationRequestScope.java
index c309516f52..fd400e26e4 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/AuthorizationRequestScope.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/AuthorizationRequestScope.java
@@ -26,6 +26,7 @@ import javax.annotation.Nullable;
import javax.ws.rs.GET;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.utils.PrincipalUtils;
/**
@@ -42,6 +43,8 @@ import org.apache.gravitino.utils.PrincipalUtils;
*/
public final class AuthorizationRequestScope implements AutoCloseable {
private static final ThreadLocal<AuthorizationRequestScope> CURRENT = new ThreadLocal<>();
+ private final TagAssignmentAuthorization tagAssignmentAuthorization =
+ TagAssignmentAuthorization.open();
@Nullable private Principal principal;
@Nullable private String metalake;
@@ -112,6 +115,7 @@ public final class AuthorizationRequestScope implements AutoCloseable {
/** Removes the scope when the invocation completes. */
@Override
public void close() {
+ tagAssignmentAuthorization.close();
CURRENT.remove();
}
}
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.java
index d81880ae89..ef157d5146 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
@@ -392,6 +392,11 @@ public class AuthorizationExpressionConstants {
((CAN_ACCESS_METADATA) && (TAG::OWNER || ANY_APPLY_TAG))
""";
+ /** Authority required to assign or remove a tag carrying an access policy. */
+ public static final String APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION =
+ "METALAKE::OWNER || (TAG::APPLY_TAG && !(ANY(DENY_APPLY_TAG, METALAKE, TAG))"
+ + " && CAN_OPERATE_METADATA_PRIVILEGE)";
+
public static final String LOAD_USER_AUTHORIZATION_EXPRESSION =
"METALAKE::OWNER || METALAKE::MANAGE_USERS || USER::SELF";
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java
index a831711c71..44f39f2354 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizationLookups.java
@@ -30,6 +30,7 @@ import org.apache.gravitino.server.authorization.MetadataIdConverter;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.utils.MetadataObjectUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.slf4j.Logger;
@@ -150,12 +151,32 @@ public class JcasbinAuthorizationLookups {
// by throwing through the loaders and translated back to Optional.empty() here. This caches
// only positive results, never a negative one. Load the same canonical name as the key,
// rather than applying the request spelling again in the loader.
- return new MetadataIdResolution(
- Optional.of(
- requestContext.computeMetadataIdIfAbsent(
- cacheKey,
- k -> metadataIdCache.get(k, ignored -> loadMetadataId(cacheObject, metalake)))),
- false);
+ Long resolved =
+ requestContext.computeMetadataIdIfAbsent(
+ cacheKey,
+ k -> metadataIdCache.get(k, ignored -> loadMetadataId(cacheObject, metalake)));
+ if (cacheObject.type() == MetadataObject.Type.TAG) {
+ Long checked =
+ TagAssignmentAuthorization.checkedIdentity(
+ NameIdentifierUtil.ofTag(metalake, cacheObject.name()));
+ if (checked != null && !checked.equals(resolved)) {
+ // An unstable identity must deny both ALLOW and DENY lookups, so a stale DENY cannot
+ // disappear when the caller also has a broader ALLOW.
+ return new MetadataIdResolution(Optional.empty(), true);
+ }
+ }
+ if (TagAssignmentAuthorization.hasTargetType(cacheObject.type())) {
+ NameIdentifier objectIdentifier = MetadataObjectUtil.toEntityIdent(metalake, cacheObject);
+ if (TagAssignmentAuthorization.wasCheckedAbsent(objectIdentifier, cacheObject.type())) {
+ return new MetadataIdResolution(Optional.empty(), true);
+ }
+ Long checkedTarget =
+ TagAssignmentAuthorization.checkedTargetIdentity(objectIdentifier, cacheObject.type());
+ if (checkedTarget != null && !checkedTarget.equals(resolved)) {
+ return new MetadataIdResolution(Optional.empty(), true);
+ }
+ }
+ return new MetadataIdResolution(Optional.of(resolved), false);
} catch (NotFoundException e) {
return new MetadataIdResolution(Optional.empty(), false);
}
@@ -192,7 +213,7 @@ public class JcasbinAuthorizationLookups {
return metadataId;
}
- /** Returns whether the catalog rules needed to normalize the object could not be resolved. */
+ /** Returns whether the metadata identity could not be resolved safely for this request. */
boolean normalizationFailed() {
return normalizationFailed;
}
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java
index a8f2a72a1e..03c4a89de2 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizationLookups.java
@@ -31,6 +31,8 @@ import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
@@ -42,11 +44,13 @@ import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
+import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.server.authorization.MetadataIdConverter;
import org.apache.gravitino.storage.relational.RelationalEntityStore;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.utils.ThrowableFunction;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -90,6 +94,41 @@ public class TestJcasbinAuthorizationLookups {
}
}
+ @Test
+ void testScopedSchemaAncestorIdentity() {
+ MetadataObject schema = MetadataObjects.parse("cat1.outer", MetadataObject.Type.SCHEMA);
+ NameIdentifier schemaIdentifier = NameIdentifier.of("ml1", "cat1", "outer");
+ CountingCache<String, Long> metadataIdCache = new CountingCache<>(100L);
+ JcasbinAuthorizationLookups lookups =
+ new JcasbinAuthorizationLookups(metadataIdCache, new CountingCache<>());
+ CatalogManager catalogs = mock(CatalogManager.class);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ doAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog<?>, Object> operation = invocation.getArgument(1);
+ return operation.apply(catalog);
+ })
+ .when(catalogs)
+ .doWithCatalog(any(), any());
+ GravitinoEnv env = mock(GravitinoEnv.class);
+ when(env.catalogManager()).thenReturn(catalogs);
+ try (MockedStatic<GravitinoEnv> envMock = mockStatic(GravitinoEnv.class);
+ TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ envMock.when(GravitinoEnv::getInstance).thenReturn(env);
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of("ml1", "cat1", "outer:inner"), Entity.EntityType.SCHEMA, null);
+ TagAssignmentAuthorization.recordSchemaAncestor(
+ schemaIdentifier, new NamespacedEntityId(100L, 1L, 2L));
+ Assertions.assertEquals(
+ Optional.of(100L),
+ lookups.resolveMetadataId(schema, "ml1", new AuthorizationRequestContext()));
+ assertScopedSchemaLookupFails(
+ lookups, schema, schemaIdentifier, new NamespacedEntityId(101L, 1L, 2L));
+ assertScopedSchemaLookupFails(lookups, schema, schemaIdentifier, null);
+ }
+ }
+
@Test
void testResolveMetadataIdUsesAtomicSharedCacheAndRequestDedup() {
MetadataObject catalog = MetadataObjects.of(Arrays.asList("cat1"), MetadataObject.Type.CATALOG);
@@ -250,6 +289,22 @@ public class TestJcasbinAuthorizationLookups {
verify(ownerMetaMapper, times(1)).selectOwnerByMetadataObjectIdAndType(100L, "TABLE");
}
+ private static void assertScopedSchemaLookupFails(
+ JcasbinAuthorizationLookups lookups,
+ MetadataObject schema,
+ NameIdentifier schemaIdentifier,
+ @Nullable NamespacedEntityId recordedAncestor) {
+ try (TagAssignmentAuthorization nested = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of("ml1", "cat1", "outer:inner"), Entity.EntityType.SCHEMA, null);
+ TagAssignmentAuthorization.recordSchemaAncestor(schemaIdentifier, recordedAncestor);
+ JcasbinAuthorizationLookups.MetadataIdResolution resolution =
+ lookups.resolveMetadataIdResult(schema, "ml1", new AuthorizationRequestContext());
+ Assertions.assertEquals(Optional.empty(), resolution.metadataId());
+ Assertions.assertTrue(resolution.normalizationFailed());
+ }
+ }
+
private static class CountingCache<K, V> implements GravitinoCache<K, V> {
private final V value;
private Optional<V> cachedValue = Optional.empty();
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
index c6e9b14ccc..0aa7b3afad 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
@@ -111,6 +111,7 @@ import org.apache.gravitino.hook.SemanticModelHookDispatcher;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.RoleEntity;
import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.meta.UserEntity;
@@ -142,6 +143,7 @@ import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.service.OwnerMetaService;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -153,6 +155,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
@@ -6029,6 +6032,379 @@ public class TestJcasbinAuthorizer {
assertNotNull(ownerRelCache, "ownerRel cache should be initialized");
}
+ @Test
+ void testAccessTagRejectsStaleCachedIdentity() throws Throwable {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ long roleId = 991L;
+ RoleEntity role =
+ mockRoleInStore(
+ roleId,
+ "oldTagGrant",
+ ImmutableList.of(
+ buildSecurableObject(
+ roleId,
+ MetadataObject.Type.TAG,
+ "sensitive",
+ Privilege.Name.APPLY_TAG,
+ "ALLOW")));
+ mockDirectUserRoles(role);
+ MetadataObject tag = MetadataObjects.of(null, "sensitive", MetadataObject.Type.TAG);
+ UserPrincipal principal = new UserPrincipal(USERNAME);
+ assertTrue(
+ jcasbinAuthorizer.authorize(
+ principal, METALAKE, tag, Privilege.Name.APPLY_TAG, new AuthorizationRequestContext()));
+ long replacementId = CATALOG_ID + 10000L;
+ withMetadataIds(
+ Map.of(tag, Optional.of(replacementId)),
+ () -> {
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordIdentity(
+ NameIdentifierUtil.ofTag(METALAKE, "sensitive"), replacementId);
+ assertFalse(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ tag,
+ Privilege.Name.APPLY_TAG,
+ new AuthorizationRequestContext()));
+ assertTrue(
+ jcasbinAuthorizer.deny(
+ principal,
+ METALAKE,
+ tag,
+ Privilege.Name.APPLY_TAG,
+ new AuthorizationRequestContext()));
+ }
+ });
+ }
+
+ @Test
+ void testAssignmentRejectsStaleCachedTargetIdentity() throws Throwable {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ long roleId = 992L;
+ RoleEntity role =
+ mockRoleInStore(
+ roleId,
+ "oldObjectGrant",
+ ImmutableList.of(
+ buildManageGrantsSecurableObject(
+ roleId, MetadataObject.Type.CATALOG, "testCatalog")));
+ mockDirectUserRoles(role);
+ MetadataObject catalog = MetadataObjects.of(null, "testCatalog", MetadataObject.Type.CATALOG);
+ UserPrincipal principal = new UserPrincipal(USERNAME);
+ assertTrue(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ long replacementId = CATALOG_ID + 10000L;
+ withMetadataIds(
+ Map.of(catalog, Optional.of(replacementId)),
+ () -> {
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of(METALAKE, "testCatalog"),
+ Entity.EntityType.CATALOG,
+ new NamespacedEntityId(replacementId, USER_METALAKE_ID));
+ assertFalse(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of(METALAKE, "testCatalog"), Entity.EntityType.CATALOG, null);
+ TagAssignmentAuthorization.recordMissingTargetAncestor(
+ new NamespacedEntityId(USER_METALAKE_ID));
+ assertFalse(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ assertTrue(
+ jcasbinAuthorizer.deny(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ }
+ });
+ }
+
+ @Test
+ void testAssignmentRejectsStaleCachedAncestorIdentity() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ long roleId = 993L;
+ RoleEntity role =
+ mockRoleInStore(
+ roleId,
+ "oldAncestorGrant",
+ ImmutableList.of(
+ buildManageGrantsSecurableObject(
+ roleId, MetadataObject.Type.CATALOG, "testCatalog")));
+ mockDirectUserRoles(role);
+ MetadataObject catalog = MetadataObjects.of(null, "testCatalog", MetadataObject.Type.CATALOG);
+ UserPrincipal principal = new UserPrincipal(USERNAME);
+ assertTrue(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of(METALAKE, "testCatalog", "testSchema", "testTable"),
+ Entity.EntityType.TABLE,
+ new NamespacedEntityId(100L, USER_METALAKE_ID, CATALOG_ID + 10000L, 99L));
+ assertFalse(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ assertTrue(
+ jcasbinAuthorizer.deny(
+ principal,
+ METALAKE,
+ catalog,
+ Privilege.Name.MANAGE_GRANTS,
+ new AuthorizationRequestContext()));
+ }
+ }
+
+ @Test
+ void testAbsentTargetRejectsStaleDirectGrant() throws Throwable {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ long roleId = 995L;
+ RoleEntity role =
+ mockRoleInStore(
+ roleId,
+ "staleTableGrant",
+ ImmutableList.of(
+ buildSecurableObject(
+ roleId,
+ MetadataObject.Type.TABLE,
+ "testCatalog.testSchema.testTable",
+ Privilege.Name.SELECT_TABLE,
+ "ALLOW")));
+ mockDirectUserRoles(role);
+ MetadataObject table =
+ MetadataObjects.parse("testCatalog.testSchema.testTable", MetadataObject.Type.TABLE);
+ UserPrincipal principal = new UserPrincipal(USERNAME);
+ assertTrue(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ table,
+ Privilege.Name.SELECT_TABLE,
+ new AuthorizationRequestContext()));
+ withMetadataIds(
+ Map.of(table, Optional.empty()),
+ () -> {
+ assertEquals(Optional.empty(), MetadataIdConverter.getID(table, METALAKE));
+ assertTrue(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ table,
+ Privilege.Name.SELECT_TABLE,
+ new AuthorizationRequestContext()));
+ try (TagAssignmentAuthorization scope = TagAssignmentAuthorization.open()) {
+ TagAssignmentAuthorization.recordTarget(
+ NameIdentifier.of(METALAKE, "testCatalog", "testSchema", "testTable"),
+ Entity.EntityType.TABLE,
+ null);
+ TagAssignmentAuthorization.recordMissingTargetAncestor(
+ new NamespacedEntityId(99L, USER_METALAKE_ID, CATALOG_ID));
+ assertFalse(
+ jcasbinAuthorizer.authorize(
+ principal,
+ METALAKE,
+ table,
+ Privilege.Name.SELECT_TABLE,
+ new AuthorizationRequestContext()));
+ assertTrue(
+ jcasbinAuthorizer.deny(
+ principal,
+ METALAKE,
+ table,
+ Privilege.Name.SELECT_TABLE,
+ new AuthorizationRequestContext()));
+ }
+ });
+ }
+
+ @Test
+ void testAccessTagExpressionWithGrantAuthority() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ long roleId = 901L;
+ RoleEntity role =
+ mockRoleInStore(
+ roleId,
+ "accessTagRole",
+ withTableParentUsage(
+ roleId,
+ buildSecurableObject(
+ roleId,
+ MetadataObject.Type.TAG,
+ "sensitive",
+ Privilege.Name.APPLY_TAG,
+ "ALLOW"),
+ buildManageGrantsSecurableObject(
+ roleId, MetadataObject.Type.CATALOG, "testCatalog")));
+ mockDirectUserRoles(role);
+ Map<Entity.EntityType, NameIdentifier> metadata = sensitiveTagMetadata();
+ Map<String, Object> path = testTablePath();
+ AuthorizationExpressionEvaluator evaluator =
+ new AuthorizationExpressionEvaluator(
+ AuthorizationExpressionConstants.APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION,
+ jcasbinAuthorizer);
+ RoleEntity broadRole =
+ mockRoleInStore(
+ 903L,
+ "broadApplyRole",
+ withTableParentUsage(
+ 903L,
+ buildSecurableObject(
+ 903L,
+ MetadataObject.Type.METALAKE,
+ METALAKE,
+ Privilege.Name.APPLY_TAG,
+ "ALLOW"),
+ buildManageGrantsSecurableObject(
+ 903L, MetadataObject.Type.CATALOG, "testCatalog")));
+ mockDirectUserRoles(broadRole);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ RoleEntity reader =
+ mockRoleInStore(
+ 905L,
+ "readerOnlyRole",
+ withTableParentUsage(
+ 905L,
+ buildSecurableObject(
+ 905L,
+ MetadataObject.Type.TABLE,
+ "testCatalog.testSchema.testTable",
+ Privilege.Name.SELECT_TABLE,
+ "ALLOW")));
+ mockDirectUserRoles(reader);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ RoleEntity tagOnly =
+ mockRoleInStore(
+ 904L,
+ "tagOnlyRole",
+ withTableParentUsage(
+ 904L,
+ buildSecurableObject(
+ 904L,
+ MetadataObject.Type.TAG,
+ "sensitive",
+ Privilege.Name.APPLY_TAG,
+ "ALLOW")));
+ mockDirectUserRoles(tagOnly);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ mockDirectUserRoles(role);
+ assertTrue(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ AuthorizationRequestContext noActiveRoles = new AuthorizationRequestContext();
+ noActiveRoles.setActiveRoles(ActiveRoles.none());
+ assertFalse(evaluator.evaluate(metadata, path, noActiveRoles, Optional.empty()));
+ RoleEntity denyRole =
+ mockRoleInStore(
+ 902L,
+ "denyAccessTagRole",
+ ImmutableList.of(
+ buildSecurableObject(
+ 902L, MetadataObject.Type.TAG, "sensitive", Privilege.Name.APPLY_TAG, "DENY")));
+ mockDirectUserRoles(role, denyRole);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ AuthorizationRequestContext narrowed = new AuthorizationRequestContext();
+ narrowed.setActiveRoles(ActiveRoles.of(Set.of("accessTagRole")));
+ assertFalse(evaluator.evaluate(metadata, path, narrowed, Optional.empty()));
+ }
+
+ @Test
+ void testAccessTagExpressionDoesNotAddServiceAdminBypass() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ AccessControlDispatcher dispatcher = mock(AccessControlDispatcher.class);
+ when(gravitinoEnv.internalAccessControlDispatcher()).thenReturn(dispatcher);
+ when(dispatcher.isServiceAdmin(USERNAME)).thenReturn(true);
+ mockDirectUserRoles();
+ AuthorizationExpressionEvaluator evaluator =
+ new AuthorizationExpressionEvaluator(
+ AuthorizationExpressionConstants.APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION,
+ jcasbinAuthorizer);
+ assertTrue(jcasbinAuthorizer.isServiceAdmin());
+ assertFalse(
+ evaluator.evaluate(
+ sensitiveTagMetadata(),
+ testTablePath(),
+ new AuthorizationRequestContext(),
+ Optional.empty()));
+ }
+
+ @Test
+ void testAccessTagExpressionWithOwnership() throws Throwable {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ MetadataObject table =
+ MetadataObjects.parse("testCatalog.testSchema.testTable", MetadataObject.Type.TABLE);
+ MetadataObject tag = MetadataObjects.of(null, "sensitive", MetadataObject.Type.TAG);
+ MetadataObject metalake = MetadataObjects.of(null, METALAKE, MetadataObject.Type.METALAKE);
+ withMetadataIds(
+ Map.of(table, Optional.of(911L), tag, Optional.of(912L), metalake, Optional.of(913L)),
+ () -> {
+ RoleEntity tagGrant =
+ mockRoleInStore(
+ 914L,
+ "ownerTagGrant",
+ withTableParentUsage(
+ 914L,
+ buildSecurableObject(
+ 914L,
+ MetadataObject.Type.TAG,
+ "sensitive",
+ Privilege.Name.APPLY_TAG,
+ "ALLOW")));
+ Map<Entity.EntityType, NameIdentifier> metadata = sensitiveTagMetadata();
+ Map<String, Object> path = testTablePath();
+ AuthorizationExpressionEvaluator evaluator =
+ new AuthorizationExpressionEvaluator(
+ AuthorizationExpressionConstants.APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION,
+ jcasbinAuthorizer);
+ GravitinoCache<Long, Optional<OwnerInfo>> owners = getOwnerRelCache(jcasbinAuthorizer);
+ owners.put(911L, Optional.of(new OwnerInfo(USER_ID, "USER")));
+ mockDirectUserRoles(tagGrant);
+ assertTrue(
+ evaluator.evaluate(
+ metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ mockDirectUserRoles();
+ assertFalse(
+ evaluator.evaluate(
+ metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ owners.invalidate(911L);
+ owners.put(912L, Optional.of(new OwnerInfo(USER_ID, "USER")));
+ assertFalse(
+ evaluator.evaluate(
+ metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ owners.put(913L, Optional.of(new OwnerInfo(USER_ID, "USER")));
+ assertTrue(
+ evaluator.evaluate(
+ metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ });
+ }
+
/** Tests {@link JcasbinAuthorizer#hasMetadataPrivilegePermission} hierarchy walk */
@Test
public void testHasMetadataPrivilegePermission() throws Exception {
@@ -6465,6 +6841,61 @@ public class TestJcasbinAuthorizer {
}
}
+ /** Returns {@code grants} followed by USE_CATALOG and USE_SCHEMA for the test table's parents. */
+ private static ImmutableList<SecurableObject> withTableParentUsage(
+ long roleId, SecurableObject... grants) {
+ return ImmutableList.<SecurableObject>builder()
+ .add(grants)
+ .add(
+ buildSecurableObject(
+ roleId, MetadataObject.Type.CATALOG, "testCatalog", USE_CATALOG, "ALLOW"))
+ .add(
+ buildSecurableObject(
+ roleId, MetadataObject.Type.SCHEMA, "testCatalog.testSchema", USE_SCHEMA, "ALLOW"))
+ .build();
+ }
+
+ private static Map<Entity.EntityType, NameIdentifier> sensitiveTagMetadata() {
+ return Map.of(
+ Entity.EntityType.METALAKE,
+ NameIdentifier.of(METALAKE),
+ Entity.EntityType.TAG,
+ NameIdentifierUtil.ofTag(METALAKE, "sensitive"));
+ }
+
+ private static Map<String, Object> testTablePath() {
+ return Map.of(
+ "p_metalake",
+ METALAKE,
+ "p_type",
+ "TABLE",
+ "p_fullName",
+ "testCatalog.testSchema.testTable");
+ }
+
+ /**
+ * Runs {@code body} with the given metadata IDs stubbed, then restores each stub to {@link
+ * #CATALOG_ID}.
+ */
+ private static void withMetadataIds(Map<MetadataObject, Optional<Long>> ids, Executable body)
+ throws Throwable {
+ ids.forEach(
+ (object, id) ->
+ metadataIdConverterMockedStatic
+ .when(() -> MetadataIdConverter.getID(object, METALAKE))
+ .thenReturn(id));
+ try {
+ body.execute();
+ } finally {
+ ids.keySet()
+ .forEach(
+ object ->
+ metadataIdConverterMockedStatic
+ .when(() -> MetadataIdConverter.getID(object, METALAKE))
+ .thenReturn(Optional.of(CATALOG_ID)));
+ }
+ }
+
@SuppressWarnings("unchecked")
private static GravitinoCache<Long, Long> getLoadedRolesCache(JcasbinAuthorizer authorizer)
throws Exception {
diff --git a/server/build.gradle.kts b/server/build.gradle.kts
index 628f6fa5c3..a1cff5e424 100644
--- a/server/build.gradle.kts
+++ b/server/build.gradle.kts
@@ -54,6 +54,9 @@ dependencies {
testCompileOnly(libs.lombok)
testImplementation(libs.commons.io)
+ testImplementation(project(":clients:client-java"))
+ testImplementation(project(":core", "testArtifacts"))
+ testImplementation(project(":integration-test-common", "testArtifacts"))
testImplementation(project(":server-common", "testArtifacts"))
testImplementation(libs.jersey.test.framework.core) {
exclude(group = "org.junit.jupiter")
@@ -74,5 +77,19 @@ tasks {
test {
environment("GRAVITINO_HOME", rootDir.path)
environment("GRAVITINO_TEST", "true")
+ useJUnitPlatform { excludeTags("server-tag-assignment-h2-test") }
}
}
+
+tasks.register<Test>("serverTagAssignmentH2Test") {
+ group = "verification"
+ description = "Runs tag assignment persistence tests against H2."
+ testClassesDirs = sourceSets["test"].output.classesDirs
+ classpath = sourceSets["test"].runtimeClasspath
+ useJUnitPlatform { includeTags("server-tag-assignment-h2-test") }
+ systemProperty("gravitino.core.test.backend", "h2")
+ systemProperty("junit.jupiter.execution.parallel.enabled", "false")
+ maxParallelForks = 1
+}
+
+tasks.named("check") { dependsOn("serverTagAssignmentH2Test") }
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
index e5e36d3cd6..12074c20d3 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
@@ -51,6 +51,7 @@ import org.apache.gravitino.exceptions.IllegalNameIdentifierException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NoSuchViewException;
import org.apache.gravitino.lineage.source.rest.LineageOperations;
import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
@@ -270,6 +271,12 @@ public class GravitinoInterceptionService implements InterceptionService {
boolean authorizeResult;
try {
authorizeResult = executor.execute(authorizationRequestContext);
+ } catch (NoSuchTagException exception) {
+ return ExceptionHandlers.handleTagException(
+ OperationType.ASSOCIATE,
+ "",
+ metalakeIdent == null ? "" : metalakeIdent.name(),
+ exception);
} catch (NoSuchTableException exception) {
NameIdentifier tableIdent = metadataContext.get(Entity.EntityType.TABLE);
if (tableIdent == null) {
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociateTagAuthorizationExecutor.java b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociateTagAuthorizationExecutor.java
index f18ab38334..d1a18cd9d3 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociateTagAuthorizationExecutor.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AssociateTagAuthorizationExecutor.java
@@ -17,23 +17,49 @@
package org.apache.gravitino.server.web.filter.authorization;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION;
import static org.apache.gravitino.server.web.filter.ParameterUtil.buildNameIdentifierForBatchAuthorization;
import static org.apache.gravitino.server.web.filter.ParameterUtil.extractFromParameters;
import com.google.common.base.Preconditions;
import java.lang.reflect.Parameter;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.function.BiPredicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.dto.requests.TagValuesAssociateRequest;
import org.apache.gravitino.dto.requests.TagsAssociateRequest;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.NotFoundException;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.policy.HiddenPolicyTag;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.authorization.MetadataIdConverter;
+import org.apache.gravitino.server.authorization.PassThroughAuthorizer;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.server.web.rest.MetadataObjectTagOperations;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+import org.apache.gravitino.tag.Tag;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
+import org.apache.gravitino.tag.TagManager;
import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.MetadataObjectUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
/**
* Metadata object authorization for {@link
@@ -44,6 +70,15 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
private final Parameter[] parameters;
private final Object[] args;
+ AuthorizationExpressionEvaluator accessTagEvaluator;
+ boolean authorizationDisabled;
+ private boolean targetCaptured;
+ BiPredicate<String, String> accessTagClassifier =
+ (metalake, tag) ->
+ isAccessTag(
+ GravitinoEnv.getInstance()
+ .tagDispatcher()
+ .listPolicyAssociationsForTag(metalake, tag));
public AssociateTagAuthorizationExecutor(
String expression,
@@ -55,6 +90,11 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
super(expression, metadataContext, pathParams, entityType);
this.parameters = parameters;
this.args = args;
+ this.accessTagEvaluator =
+ new AuthorizationExpressionEvaluator(APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION);
+ this.authorizationDisabled =
+ GravitinoAuthorizerProvider.getInstance().getGravitinoAuthorizer()
+ instanceof PassThroughAuthorizer;
}
@Override
@@ -72,6 +112,18 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
request instanceof TagsAssociateRequest || request instanceof TagValuesAssociateRequest,
"Only tag can use AssociateTagAuthorizationExecutor, please contact the administrator.");
+ boolean validRequest = true;
+ try {
+ if (request instanceof TagsAssociateRequest) {
+ ((TagsAssociateRequest) request).validate();
+ } else {
+ ((TagValuesAssociateRequest) request).validate();
+ }
+ } catch (IllegalArgumentException e) {
+ // The resource rejects invalid requests before mutation; preserve its normal error response.
+ validRequest = false;
+ }
+
TagValue[] tagsToAdd;
TagValue[] tagsToRemove;
if (request instanceof TagsAssociateRequest) {
@@ -85,8 +137,16 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
}
// Authorize both 'tagsToAdd' and 'tagsToRemove' fields.
- return authorizeTag(tagsToAdd, context, targetType)
- && authorizeTag(tagsToRemove, context, targetType);
+ return authorizeTag(tagsToAdd, context, targetType, validRequest)
+ && authorizeTag(tagsToRemove, context, targetType, validRequest);
+ }
+
+ static boolean isAccessTag(RelationalEntity<?>[] associations) {
+ return Arrays.stream(associations)
+ .anyMatch(
+ association ->
+ ((PolicyEntity) association.targetEntity()).policyType()
+ == Policy.BuiltInType.ACCESS_CONTROL);
}
/**
@@ -99,7 +159,10 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
* @return {@code true} if all tags in the field pass authorization; {@code false} otherwise.
*/
private boolean authorizeTag(
- TagValue[] tagValues, AuthorizationRequestContext context, Entity.EntityType targetType) {
+ TagValue[] tagValues,
+ AuthorizationRequestContext context,
+ Entity.EntityType targetType,
+ boolean validRequest) {
// Treat null or empty arrays as no-op (implicitly authorized)
if (tagValues == null) {
@@ -111,9 +174,52 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
Map<Entity.EntityType, NameIdentifier> currentContext = new HashMap<>(this.metadataContext);
buildNameIdentifierForBatchAuthorization(currentContext, tagValue.name(), targetType);
- boolean authorized =
- authorizationExpressionEvaluator.evaluate(
- currentContext, pathParams, context, entityType);
+ String metalake = currentContext.get(Entity.EntityType.METALAKE).name();
+ if (validRequest
+ && !authorizationDisabled
+ && HiddenPolicyTag.isReservedName(tagValue.name())) {
+ throw new NoSuchTagException(
+ "Tag with name %s under metalake %s does not exist", tagValue.name(), metalake);
+ }
+ boolean accessTag = false;
+ if (validRequest && !authorizationDisabled) {
+ try {
+ if (TagAssignmentAuthorization.isActive()) {
+ captureTargetIdentity();
+ Tag tag =
+ GravitinoEnv.getInstance()
+ .internalTagDispatcher()
+ .getTag(metalake, tagValue.name());
+ Preconditions.checkState(tag instanceof HasIdentifier, "Tag identity is unavailable");
+ TagAssignmentAuthorization.recordIdentity(
+ NameIdentifierUtil.ofTag(metalake, tagValue.name()),
+ ((HasIdentifier) tag).id(),
+ tag.name());
+ }
+ accessTag = accessTagClassifier.test(metalake, tagValue.name());
+ } catch (NoSuchTagException missing) {
+ // Missing tags use the original authorization and are rechecked during the write.
+ }
+ }
+ if (validRequest && !authorizationDisabled && !accessTag) {
+ TagAssignmentAuthorization.requireDescriptive(
+ NameIdentifierUtil.ofTag(metalake, tagValue.name()));
+ }
+ context.setOriginalAuthorizationExpression(
+ accessTag ? APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION : expression);
+ AuthorizationExpressionEvaluator evaluator =
+ accessTag ? accessTagEvaluator : authorizationExpressionEvaluator;
+ Map<String, Object> evaluationPath = pathParams;
+ if (accessTag && entityType.isPresent() && entityType.get().equalsIgnoreCase("column")) {
+ MetadataObject column =
+ MetadataObjects.parse(
+ (String) pathParams.get("p_fullName"), MetadataObject.Type.COLUMN);
+ MetadataObject table = MetadataObjects.parent(column);
+ evaluationPath = new HashMap<>(pathParams);
+ evaluationPath.put("p_type", table.type().name());
+ evaluationPath.put("p_fullName", table.fullName());
+ }
+ boolean authorized = evaluator.evaluate(currentContext, evaluationPath, context, entityType);
if (!authorized) {
return false; // Fail fast on first unauthorized tag
@@ -122,6 +228,76 @@ public class AssociateTagAuthorizationExecutor extends CommonAuthorizerExecutor
return true;
}
+ private void captureTargetIdentity() {
+ if (targetCaptured || entityType.isEmpty()) {
+ return;
+ }
+ targetCaptured = true;
+ MetadataObject.Type objectType = MetadataObject.Type.valueOf(entityType.get());
+ if (!TagManager.SUPPORTED_METADATA_OBJECT_TYPES_FOR_TAGS.contains(objectType)) {
+ return;
+ }
+ Entity.EntityType type = MetadataObjectUtil.toEntityType(objectType);
+ NameIdentifier identifier = metadataContext.get(type);
+ String metalake = metadataContext.get(Entity.EntityType.METALAKE).name();
+ MetadataObject original = NameIdentifierUtil.toMetadataObject(identifier, type);
+ MetadataObject normalized = original;
+ try {
+ normalized = MetadataIdConverter.normalizeMetadataObject(normalized, metalake);
+ NameIdentifier normalizedIdentifier = MetadataObjectUtil.toEntityIdent(metalake, normalized);
+ TagAssignmentAuthorization.recordTarget(
+ normalizedIdentifier, type, EntityIdService.getEntityIds(normalizedIdentifier, type));
+ } catch (NotFoundException missing) {
+ TagAssignmentAuthorization.recordTarget(
+ MetadataObjectUtil.toEntityIdent(metalake, normalized), type, null);
+ captureClosestExistingAncestor(normalized, metalake);
+ }
+ captureSchemaAncestors(original, metalake);
+ }
+
+ private void captureSchemaAncestors(MetadataObject target, String metalake) {
+ List<MetadataObject> parents =
+ new ArrayList<>(MetadataObjectUtil.getParentMetadataObjects(target));
+ Collections.reverse(parents);
+ for (MetadataObject parent : parents) {
+ if (parent.type() != MetadataObject.Type.SCHEMA) {
+ continue;
+ }
+ MetadataObject normalized = parent;
+ try {
+ normalized = MetadataIdConverter.normalizeMetadataObject(parent, metalake);
+ NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, normalized);
+ TagAssignmentAuthorization.recordSchemaAncestor(
+ identifier, EntityIdService.getEntityIds(identifier, Entity.EntityType.SCHEMA));
+ } catch (NotFoundException missing) {
+ TagAssignmentAuthorization.recordSchemaAncestor(
+ MetadataObjectUtil.toEntityIdent(metalake, normalized), null);
+ }
+ }
+ }
+
+ private void captureClosestExistingAncestor(MetadataObject target, String metalake) {
+ List<MetadataObject> parents =
+ new ArrayList<>(MetadataObjectUtil.getParentMetadataObjects(target));
+ parents.add(MetadataObjects.of(null, metalake, MetadataObject.Type.METALAKE));
+ EnumSet<MetadataObject.Type> seen = EnumSet.of(target.type());
+ for (MetadataObject parent : parents) {
+ if (!seen.add(parent.type())) {
+ continue;
+ }
+ try {
+ MetadataObject normalized = MetadataIdConverter.normalizeMetadataObject(parent, metalake);
+ Entity.EntityType type = MetadataObjectUtil.toEntityType(normalized.type());
+ TagAssignmentAuthorization.recordMissingTargetAncestor(
+ EntityIdService.getEntityIds(
+ MetadataObjectUtil.toEntityIdent(metalake, normalized), type));
+ return;
+ } catch (NotFoundException missing) {
+ // Try the next physical ancestor. A missing target must not reuse an old target grant.
+ }
+ }
+ }
+
private static TagValue[] toNoValue(String[] tags) {
if (tags == null) {
return new TagValue[0];
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
index 9c4e0fc406..571a99df5e 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
@@ -23,6 +23,7 @@ import static org.apache.gravitino.server.authorization.expression.Authorization
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.TEST_CATALOG_CONNECTION_WITH_CHANGES_AUTHORIZATION_EXPRESSION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
@@ -56,6 +57,7 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.auth.ActiveRoles;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
@@ -89,12 +91,17 @@ import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NoSuchViewException;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.listener.EventBus;
import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metalake.MetalakeManager;
+import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.SQLRepresentation;
@@ -131,8 +138,11 @@ import org.apache.gravitino.server.web.rest.SecretsProviderOperations;
import org.apache.gravitino.server.web.rest.SemanticModelMetricOperations;
import org.apache.gravitino.server.web.rest.SemanticModelOperations;
import org.apache.gravitino.server.web.rest.TableOperations;
+import org.apache.gravitino.server.web.rest.TagOperations;
import org.apache.gravitino.server.web.rest.ViewOperations;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
import org.apache.gravitino.tag.TagDispatcher;
+import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.gravitino.utils.RequestContext;
import org.apache.gravitino.utils.ThrowableFunction;
@@ -1584,6 +1594,108 @@ public class TestGravitinoInterceptionService {
}
}
+ @Test
+ void testMixedTagBatchesAreRejectedBeforeMutation() throws Throwable {
+ try (TesterRequestMocks mocks = new TesterRequestMocks();
+ MockedStatic<EntityIdService> ids = mockStatic(EntityIdService.class)) {
+ ids.when(() -> EntityIdService.getEntityIds(any(), any()))
+ .thenReturn(new NamespacedEntityId(2L, 1L));
+ when(mocks.authorizer.authorize(any(), any(), any(), any(), any())).thenReturn(true);
+ TagDispatcher dispatcher = mock(TagDispatcher.class);
+ when(mocks.env.tagDispatcher()).thenReturn(dispatcher);
+ when(mocks.env.internalTagDispatcher()).thenReturn(dispatcher);
+ TagEntity descriptiveTag = mock(TagEntity.class);
+ TagEntity accessTag = mock(TagEntity.class);
+ when(descriptiveTag.id()).thenReturn(1L);
+ when(accessTag.id()).thenReturn(2L);
+ when(dispatcher.getTag("testMetalake", "descriptive")).thenReturn(descriptiveTag);
+ when(dispatcher.getTag("testMetalake", "access")).thenReturn(accessTag);
+ RelationalEntity<?> relation = mock(RelationalEntity.class);
+ PolicyEntity policy = mock(PolicyEntity.class);
+ doReturn(policy).when(relation).targetEntity();
+ when(policy.policyType()).thenReturn(Policy.BuiltInType.ACCESS_CONTROL);
+ when(dispatcher.listPolicyAssociationsForTag("testMetalake", "descriptive"))
+ .thenReturn(new RelationalEntity<?>[0]);
+ when(dispatcher.listPolicyAssociationsForTag("testMetalake", "access"))
+ .thenReturn(new RelationalEntity<?>[] {relation});
+ Object[] requests = {
+ new TagsAssociateRequest(new String[] {"descriptive", "access"}, null),
+ new TagValuesAssociateRequest(
+ new TagValue[] {TagValue.noValue("descriptive"), TagValue.of("access", "finance")},
+ null),
+ new TagsAssociateRequest(new String[] {"descriptive", "access"}, null)
+ };
+ for (int i = 0; i < requests.length; i++) {
+ Object request = requests[i];
+ String methodName =
+ request instanceof TagsAssociateRequest
+ ? "associateTagsForObject"
+ : "associateTagValuesForObject";
+ Class<?> resource = i == 2 ? TagOperations.class : MetadataObjectTagOperations.class;
+ Method method =
+ resource.getMethod(
+ methodName, String.class, String.class, String.class, request.getClass());
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(new Object[] {"testMetalake", "catalog", "object1", request});
+ Response response =
+ (Response)
+ new GravitinoInterceptionService()
+ .getMethodInterceptors(method)
+ .get(0)
+ .invoke(invocation);
+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
+ verify(invocation, never()).proceed();
+ }
+ }
+ }
+
+ @Test
+ void testHiddenTagNamesCannotBeProbed() throws Throwable {
+ try (TesterRequestMocks mocks = new TesterRequestMocks()) {
+ TagDispatcher dispatcher = mock(TagDispatcher.class);
+ when(mocks.env.tagDispatcher()).thenReturn(dispatcher);
+ when(dispatcher.listPolicyAssociationsForTag("testMetalake", "gravitino_hidden_123"))
+ .thenReturn(new RelationalEntity<?>[0]);
+ when(dispatcher.listPolicyAssociationsForTag("testMetalake", "gravitino_hidden_999"))
+ .thenThrow(new NoSuchTagException("missing"));
+ Method method =
+ MetadataObjectTagOperations.class.getMethod(
+ "associateTagsForObject",
+ String.class,
+ String.class,
+ String.class,
+ TagsAssociateRequest.class);
+ MethodInterceptor interceptor =
+ new GravitinoInterceptionService().getMethodInterceptors(method).get(0);
+ MethodInvocation existing = mock(MethodInvocation.class);
+ when(existing.getMethod()).thenReturn(method);
+ when(existing.getArguments())
+ .thenReturn(
+ new Object[] {
+ "testMetalake",
+ "catalog",
+ "object1",
+ new TagsAssociateRequest(new String[] {"gravitino_hidden_123"}, null)
+ });
+ MethodInvocation missing = mock(MethodInvocation.class);
+ when(missing.getMethod()).thenReturn(method);
+ when(missing.getArguments())
+ .thenReturn(
+ new Object[] {
+ "testMetalake",
+ "catalog",
+ "object1",
+ new TagsAssociateRequest(new String[] {"gravitino_hidden_999"}, null)
+ });
+ Response existingResponse = (Response) interceptor.invoke(existing);
+ Response missingResponse = (Response) interceptor.invoke(missing);
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), existingResponse.getStatus());
+ assertEquals(missingResponse.getStatus(), existingResponse.getStatus());
+ }
+ }
+
@Test
public void testInvalidV2TagAssociationBodyReturnsBadRequestAfterAuthorization()
throws Throwable {
@@ -2538,6 +2650,38 @@ public class TestGravitinoInterceptionService {
return authorizer;
}
+ private static class TesterRequestMocks implements AutoCloseable {
+ private final MockedStatic<PrincipalUtils> principals = mockStatic(PrincipalUtils.class);
+ private final MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ private final MockedStatic<AuthorizationUtils> authorizationUtils =
+ mockStatic(AuthorizationUtils.class);
+ private final MockedStatic<GravitinoEnv> environments = mockStatic(GravitinoEnv.class);
+ private final GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ private final GravitinoEnv env = mock(GravitinoEnv.class);
+
+ private TesterRequestMocks() {
+ principals.when(PrincipalUtils::getCurrentPrincipal).thenReturn(new UserPrincipal("tester"));
+ principals.when(PrincipalUtils::getCurrentUserName).thenReturn("tester");
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+ authorizationUtils
+ .when(() -> AuthorizationUtils.checkCurrentUser(any(), any(), any()))
+ .thenAnswer(invocation -> null);
+ environments.when(GravitinoEnv::getInstance).thenReturn(env);
+ when(env.eventBus()).thenReturn(mock(EventBus.class));
+ }
+
+ @Override
+ public void close() {
+ environments.close();
+ authorizationUtils.close();
+ providers.close();
+ principals.close();
+ }
+ }
+
private static class MockGravitinoAuthorizer implements GravitinoAuthorizer {
@Override
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestTagAssignmentAuthorizationH2.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestTagAssignmentAuthorizationH2.java
new file mode 100644
index 0000000000..8affa25541
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestTagAssignmentAuthorizationH2.java
@@ -0,0 +1,1626 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.server.web.filter;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Response;
+import org.aopalliance.intercept.MethodInvocation;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.UserGroup;
+import org.apache.gravitino.UserPrincipal;
+import org.apache.gravitino.auth.ActiveRoles;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.cache.NoOpsCache;
+import org.apache.gravitino.catalog.CatalogDispatcher;
+import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.SchemaDispatcher;
+import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.connector.capability.CapabilityResult;
+import org.apache.gravitino.dto.requests.TagValuesAssociateRequest;
+import org.apache.gravitino.dto.requests.TagsAssociateRequest;
+import org.apache.gravitino.dto.responses.TagResponse;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.policy.AllValuesSelector;
+import org.apache.gravitino.policy.HiddenPolicyTag;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.policy.PolicyContents;
+import org.apache.gravitino.policy.PolicyManager;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.authorization.PassThroughAuthorizer;
+import org.apache.gravitino.server.authorization.jcasbin.JcasbinAuthorizer;
+import org.apache.gravitino.server.web.rest.MetadataObjectTagOperations;
+import org.apache.gravitino.server.web.rest.TagOperations;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.EntityChangeLogListener;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.service.OwnerMetaService;
+import org.apache.gravitino.tag.TagAssignmentAuthorization;
+import org.apache.gravitino.tag.TagManager;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.gravitino.utils.ThrowableFunction;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.TestTemplate;
+import org.mockito.MockedStatic;
+import org.mockito.stubbing.Answer;
+
+/** Verifies tag assignment authorization against persisted H2 metadata. */
+@Tag("server-tag-assignment-h2-test")
+public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
+ @TestTemplate
+ void testCreatedAccessTagInvalidatesMissingTagAuthorization() throws Throwable {
+ String metalake = "missing_tag_auth_h2";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, "policy", Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ UserPrincipal principal = new UserPrincipal("tester");
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("internalCatalogDispatcher", existingCatalogs());
+ security.mockAuthorizer(MetadataObject.Type.TAG, MetadataObject.Type.CATALOG);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"created"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Response response =
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "catalog",
+ "catalog",
+ request,
+ () ->
+ runAsSecondWriter(
+ principal,
+ () -> {
+ createAndInsertTagEntity("created", "", metalake);
+ tags.addPolicyForTag(
+ metalake, "created", "policy", AllValuesSelector.get());
+ }));
+ assertEquals(409, response.getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "created").length);
+ }
+ }
+
+ @TestTemplate
+ void testPaddedTagNameKeepsMixedRequestBehavior() throws Throwable {
+ Config config = GravitinoEnv.getInstance().config();
+ try (Connection connection =
+ DriverManager.getConnection(
+ config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL),
+ config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER),
+ config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD));
+ Statement statement = connection.createStatement()) {
+ statement.execute("ALTER TABLE tag_meta ALTER COLUMN tag_name CHAR(5) NOT NULL");
+ try {
+ String metalake = "pad_test";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertTagEntity("label", "", metalake);
+ createAndInsertTagEntity("plain", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ UserPrincipal principal = new UserPrincipal("tester");
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("internalCatalogDispatcher", existingCatalogs());
+ security.mockAuthorizer(MetadataObject.Type.METALAKE);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"plain"}, new String[] {"label "});
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(operations, "associateTagsForObject", metalake, request)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "plain").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[0], new String[] {"plain"}))
+ .getStatus());
+ Response replaced =
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "catalog",
+ "catalog",
+ request,
+ () ->
+ runAsSecondWriter(
+ principal,
+ () -> {
+ assertTrue(tags.deleteTag(metalake, "label"));
+ createAndInsertTagEntity("label", "", metalake);
+ }));
+ assertEquals(409, replaced.getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "plain").length);
+ }
+ } finally {
+ statement.execute("ALTER TABLE tag_meta ALTER COLUMN tag_name VARCHAR(128) NOT NULL");
+ }
+ }
+ }
+
+ @TestTemplate
+ void testConcurrentBindingInvalidatesDescriptiveAssignment() throws Throwable {
+ String metalake = "tag_auth_h2";
+ String policyName = "policy";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertTagEntity("visible", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, policyName, Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ UserPrincipal principal = new UserPrincipal("tester");
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("internalCatalogDispatcher", existingCatalogs());
+ security.mockAuthorizer(MetadataObject.Type.TAG, MetadataObject.Type.CATALOG);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ MethodInvocation invocation =
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", request},
+ ignored -> {
+ runAsSecondWriter(
+ principal,
+ () ->
+ tags.addPolicyForTag(
+ metalake, "visible", policyName, AllValuesSelector.get()));
+ return operations.associateTagsForObject(metalake, "catalog", "catalog", request);
+ });
+ Response response = intercept(method, invocation);
+ assertEquals(409, response.getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertTrue(hasVisibleBinding(policies, metalake, policyName));
+ }
+ }
+
+ @TestTemplate
+ void testRecreatedAccessTagCannotReusePriorGrant() throws Throwable {
+ String metalake = "tag_auth_h2";
+ String policyName = "policy";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertTagEntity("visible", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, policyName, Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ UserPrincipal principal = new UserPrincipal("tester");
+ AtomicBoolean oldTagGranted = new AtomicBoolean(true);
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides.setPolicyAndTagDispatchers(policies, tags);
+ tags.addPolicyForTag(metalake, "visible", policyName, AllValuesSelector.get());
+ overrides.set("internalCatalogDispatcher", existingCatalogs());
+ GravitinoAuthorizer authorizer =
+ security.mockAuthorizer(MetadataObject.Type.TAG, MetadataObject.Type.CATALOG);
+ when(authorizer.authorize(any(), any(), any(), any(), any()))
+ .thenAnswer(
+ inv ->
+ oldTagGranted.get()
+ && ((MetadataObject) inv.getArgument(2)).type() == MetadataObject.Type.TAG
+ && inv.getArgument(3) == Privilege.Name.APPLY_TAG);
+ when(authorizer.hasMetadataPrivilegePermission(any(), any(), any(), any())).thenReturn(true);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ MethodInvocation invocation =
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", request},
+ ignored -> {
+ runAsSecondWriter(
+ principal,
+ () -> {
+ assertTrue(tags.deleteTag(metalake, "visible"));
+ tags.createTag(metalake, "visible", "replacement", Map.of());
+ tags.addPolicyForTag(
+ metalake, "visible", policyName, AllValuesSelector.get());
+ oldTagGranted.set(false);
+ });
+ return operations.associateTagsForObject(metalake, "catalog", "catalog", request);
+ });
+ Response response = intercept(method, invocation);
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertFalse(oldTagGranted.get());
+ assertEquals(409, response.getStatus(), "replacement must not reuse the old tag grant");
+ assertTrue(hasVisibleBinding(policies, metalake, policyName));
+ }
+ }
+
+ @TestTemplate
+ void testDeletedAuthorizedTagDoesNotPartiallyAssignBatch() throws Throwable {
+ String metalake = "tag_auth_h2";
+ String policyName = "policy";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertTagEntity("visible", "", metalake);
+ createAndInsertTagEntity("other", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, policyName, Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ UserPrincipal principal = new UserPrincipal("tester");
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("internalCatalogDispatcher", existingCatalogs());
+ security.mockAuthorizer(MetadataObject.Type.TAG, MetadataObject.Type.CATALOG);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"visible", "other"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ MethodInvocation invocation =
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", request},
+ ignored -> {
+ runAsSecondWriter(principal, () -> assertTrue(tags.deleteTag(metalake, "visible")));
+ return operations.associateTagsForObject(metalake, "catalog", "catalog", request);
+ });
+ Response response = intercept(method, invocation);
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "other").length);
+ assertEquals(
+ 409,
+ response.getStatus(),
+ "a disappeared authorized tag must not partially mutate the batch");
+ }
+ }
+
+ @TestTemplate
+ void testRecreatedCatalogCannotReusePriorGrant() throws Throwable {
+ String metalake = "tag_auth_h2";
+ String policyName = "policy";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertTagEntity("visible", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, policyName, Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ UserPrincipal principal = new UserPrincipal("tester");
+ AtomicBoolean oldObjectGranted = new AtomicBoolean(true);
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides.setPolicyAndTagDispatchers(policies, tags);
+ tags.addPolicyForTag(metalake, "visible", policyName, AllValuesSelector.get());
+ overrides.set("internalCatalogDispatcher", existingCatalogs());
+ GravitinoAuthorizer authorizer =
+ security.mockAuthorizer(MetadataObject.Type.TAG, MetadataObject.Type.CATALOG);
+ when(authorizer.authorize(any(), any(), any(), any(), any()))
+ .thenAnswer(
+ inv ->
+ ((MetadataObject) inv.getArgument(2)).type() == MetadataObject.Type.TAG
+ && inv.getArgument(3) == Privilege.Name.APPLY_TAG);
+ when(authorizer.hasMetadataPrivilegePermission(any(), any(), any(), any()))
+ .thenAnswer(inv -> oldObjectGranted.get());
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ MethodInvocation invocation =
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", request},
+ ignored -> {
+ runAsSecondWriter(
+ principal,
+ () -> {
+ assertTrue(
+ store.delete(
+ NameIdentifier.of(metalake, "catalog"), Entity.EntityType.CATALOG));
+ createAndInsertCatalog(metalake, "catalog");
+ oldObjectGranted.set(false);
+ });
+ return operations.associateTagsForObject(metalake, "catalog", "catalog", request);
+ });
+ Response response = intercept(method, invocation);
+ assertFalse(oldObjectGranted.get());
+ assertEquals(409, response.getStatus(), "replacement must not reuse the old object grant");
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertTrue(hasVisibleBinding(policies, metalake, policyName));
+ }
+ }
+
+ @TestTemplate
+ void testReviewRequestedTagAuthority() throws Throwable {
+ String metalake = "review_auth_h2";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertSchema(metalake, "catalog", "schema");
+ backend.insert(
+ TableEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("coltable")
+ .withNamespace(Namespace.of(metalake, "catalog", "schema"))
+ .withColumns(
+ List.of(
+ ColumnEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("c1")
+ .withPosition(0)
+ .withComment("c")
+ .withDataType(Types.IntegerType.get())
+ .withNullable(true)
+ .withAutoIncrement(false)
+ .withAuditInfo(AUDIT_INFO)
+ .build()))
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ createAndInsertTagEntity("visible", "", metalake);
+ createAndInsertTagEntity("label", "", metalake);
+ RelationalEntityStore store =
+ new RelationalEntityStore() {
+ @Override
+ public void registerEntityChangeLogListener(EntityChangeLogListener listener) {}
+
+ @Override
+ public void unregisterEntityChangeLogListener(EntityChangeLogListener listener) {}
+ };
+ Config config = new Config(false) {};
+ config.set(Configs.ENABLE_AUTHORIZATION, true);
+ config.set(Configs.GRAVITINO_AUTHORIZATION_CHANGE_POLL_INTERVAL_SECS, 3600L);
+ wireStore(store, config);
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ putPolicy(store, metalake, "policy", Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ long roleId =
+ putRole(
+ store,
+ metalake,
+ "role",
+ List.of(
+ SecurableObjects.ofTag("visible", List.of(Privileges.ApplyTag.allow())),
+ SecurableObjects.ofCatalog(
+ "catalog",
+ List.of(Privileges.ManageGrants.allow(), Privileges.UseCatalog.allow()))));
+ long governanceRoleId =
+ putRole(
+ store,
+ metalake,
+ "governanceRole",
+ List.of(
+ SecurableObjects.ofCatalog(
+ "catalog",
+ List.of(Privileges.UseCatalog.allow(), Privileges.ManageGrants.allow())),
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ "schema",
+ List.of(Privileges.UseSchema.allow()))));
+ long metalakeDenyRoleId =
+ putRole(
+ store,
+ metalake,
+ "denyMetalake",
+ List.of(SecurableObjects.ofMetalake(metalake, List.of(Privileges.ApplyTag.deny()))));
+ SecurableObject columnCatalog =
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow()));
+ SecurableObject columnSchema =
+ SecurableObjects.ofSchema(columnCatalog, "schema", List.of(Privileges.UseSchema.allow()));
+ long tableGrantRoleId =
+ putRole(
+ store,
+ metalake,
+ "tableGrant",
+ List.of(
+ columnCatalog,
+ columnSchema,
+ SecurableObjects.ofTable(
+ columnSchema, "coltable", List.of(Privileges.ManageGrants.allow())),
+ SecurableObjects.ofTag("visible", List.of(Privileges.ApplyTag.allow()))));
+ putUser(
+ store,
+ metalake,
+ "deniedMetalake",
+ List.of(roleId, metalakeDenyRoleId),
+ List.of("role", "denyMetalake"));
+ putUser(store, metalake, "tableGrant", List.of(tableGrantRoleId), List.of("tableGrant"));
+ putUser(store, metalake, "allowed", List.of(roleId), List.of("role"));
+ putUser(store, metalake, "governor", List.of(governanceRoleId), List.of("governanceRole"));
+ setOwner(
+ metalake, NameIdentifierUtil.ofTag(metalake, "label"), Entity.EntityType.TAG, "governor");
+ setOwner(
+ metalake, NameIdentifierUtil.ofTag(metalake, "visible"), Entity.EntityType.TAG, "governor");
+ GravitinoEnv env = GravitinoEnv.getInstance();
+ try (EnvOverride overrides =
+ new EnvOverride(
+ "config",
+ "entityStore",
+ "gravitinoAuthorizer",
+ "policyDispatcher",
+ "tagDispatcher",
+ "internalTagDispatcher",
+ "internalCatalogDispatcher",
+ "internalSchemaDispatcher",
+ "internalTableDispatcher",
+ "catalogManager",
+ "eventBus");
+ JcasbinAuthorizer authorizer = new JcasbinAuthorizer();
+ MockedStatic<PrincipalUtils> principals = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class)) {
+ overrides
+ .set("config", config)
+ .set("entityStore", store)
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("eventBus", mock(EventBus.class))
+ .set("internalCatalogDispatcher", existingCatalogs());
+ SchemaDispatcher schemas = mock(SchemaDispatcher.class);
+ when(schemas.schemaExists(any())).thenReturn(true);
+ overrides.set("internalSchemaDispatcher", schemas);
+ TableDispatcher tables = mock(TableDispatcher.class);
+ when(tables.tableExists(any())).thenReturn(true);
+ overrides.set("internalTableDispatcher", tables);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ overrides.set("catalogManager", catalogManagerFor(catalog));
+ AtomicReference<UserPrincipal> current = new AtomicReference<>(new UserPrincipal("governor"));
+ principals.when(PrincipalUtils::getCurrentPrincipal).thenAnswer(i -> current.get());
+ principals.when(PrincipalUtils::getCurrentUserName).thenAnswer(i -> current.get().getName());
+ principals.when(() -> PrincipalUtils.doAs(any(), any())).thenCallRealMethod();
+ tags.addPolicyForTag(metalake, "visible", "policy", AllValuesSelector.get());
+ authorizer.initialize();
+ env.setGravitinoAuthorizer(authorizer);
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ TagsAssociateRequest add = new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ current.set(new UserPrincipal("governor"));
+ TagsAssociateRequest labelAdd =
+ new TagsAssociateRequest(new String[] {"label"}, new String[0]);
+ TagsAssociateRequest labelRemove =
+ new TagsAssociateRequest(new String[0], new String[] {"label"});
+ assertEquals(
+ 200,
+ invokeRealTagRoute(operations, "associateTagsForObject", metalake, labelAdd).getStatus());
+ assertEquals(
+ 200,
+ invokeRealTagRoute(operations, "associateTagsForObject", metalake, labelRemove)
+ .getStatus());
+ assertEquals(
+ 403, invokeRealTagRoute(operations, "associateTagsForObject", metalake, add).getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("deniedMetalake"));
+ assertEquals(
+ 403, invokeRealTagRoute(operations, "associateTagsForObject", metalake, add).getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200, invokeRealTagRoute(operations, "associateTagsForObject", metalake, add).getStatus());
+ TagsAssociateRequest catalogRemove =
+ new TagsAssociateRequest(new String[0], new String[] {"visible"});
+ current.set(new UserPrincipal("deniedMetalake"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(operations, "associateTagsForObject", metalake, catalogRemove)
+ .getStatus());
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(operations, "associateTagsForObject", metalake, catalogRemove)
+ .getStatus());
+ current.set(new UserPrincipal("tableGrant"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ add)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ TagsAssociateRequest remove =
+ new TagsAssociateRequest(new String[0], new String[] {"visible"});
+ current.set(new UserPrincipal("governor"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ current.set(new UserPrincipal("tableGrant"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ }
+ }
+
+ @TestTemplate
+ void testActualJcasbinTagAssignment() throws Throwable {
+ String metalake = "real_auth_h2";
+ String foreignMetalake = "foreign_auth_h2";
+ createAndInsertMakeLake(metalake);
+ createAndInsertMakeLake(foreignMetalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertSchema(metalake, "catalog", "schema");
+ createAndInsertTableEntity(Namespace.of(metalake, "catalog", "schema"), "table");
+ backend.insert(
+ TableEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("coltable")
+ .withNamespace(Namespace.of(metalake, "catalog", "schema"))
+ .withColumns(
+ List.of(
+ ColumnEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("c1")
+ .withPosition(0)
+ .withComment("c")
+ .withDataType(Types.IntegerType.get())
+ .withNullable(true)
+ .withAutoIncrement(false)
+ .withAuditInfo(AUDIT_INFO)
+ .build()))
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ createAndInsertSchema(metalake, "catalog", "outer:inner");
+ createAndInsertTableEntity(Namespace.of(metalake, "catalog", "outer:inner"), "nested_table");
+ createAndInsertSchema(metalake, "catalog", "MiXeD");
+ createAndInsertTableEntity(Namespace.of(metalake, "catalog", "MiXeD"), "MiXeDTbl");
+ createAndInsertTagEntity("visible", "", metalake);
+ createAndInsertTagEntity("label", "", metalake);
+ createAndInsertTagEntity("foreign_tag", "", foreignMetalake);
+ RelationalEntityStore store =
+ new RelationalEntityStore() {
+ @Override
+ public void registerEntityChangeLogListener(EntityChangeLogListener listener) {}
+
+ @Override
+ public void unregisterEntityChangeLogListener(EntityChangeLogListener listener) {}
+ };
+ Config config = new Config(false) {};
+ config.set(Configs.ENABLE_AUTHORIZATION, true);
+ config.set(Configs.GRAVITINO_AUTHORIZATION_CHANGE_POLL_INTERVAL_SECS, 3600L);
+ wireStore(store, config);
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ PolicyEntity policy =
+ putPolicy(store, metalake, "policy", Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ long roleId =
+ putRole(
+ store,
+ metalake,
+ "role",
+ List.of(
+ SecurableObjects.ofTag("visible", List.of(Privileges.ApplyTag.allow())),
+ SecurableObjects.ofCatalog(
+ "catalog",
+ List.of(Privileges.ManageGrants.allow(), Privileges.UseCatalog.allow())),
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ "schema",
+ List.of(Privileges.UseSchema.allow())),
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ "outer",
+ List.of(Privileges.UseSchema.allow())),
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ "MiXeD",
+ List.of(Privileges.UseSchema.allow()))));
+ long denyRoleId =
+ putRole(
+ store,
+ metalake,
+ "denyTag",
+ List.of(SecurableObjects.ofTag("visible", List.of(Privileges.ApplyTag.deny()))));
+ long tagOnlyRoleId =
+ putRole(
+ store,
+ metalake,
+ "tagOnly",
+ List.of(
+ SecurableObjects.ofTag("visible", List.of(Privileges.ApplyTag.allow())),
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow())),
+ "schema",
+ List.of(Privileges.UseSchema.allow()))));
+ long governanceRoleId =
+ putRole(
+ store,
+ metalake,
+ "governanceRole",
+ List.of(SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow()))));
+ SecurableObject labelCatalog =
+ SecurableObjects.ofCatalog("catalog", List.of(Privileges.UseCatalog.allow()));
+ SecurableObject labelSchema =
+ SecurableObjects.ofSchema(labelCatalog, "schema", List.of(Privileges.UseSchema.allow()));
+ long labelRoleId =
+ putRole(
+ store,
+ metalake,
+ "labelColumn",
+ List.of(
+ labelCatalog,
+ labelSchema,
+ SecurableObjects.ofTable(
+ labelSchema, "coltable", List.of(Privileges.SelectTable.allow())),
+ SecurableObjects.ofTag("label", List.of(Privileges.ApplyTag.allow()))));
+ putUser(store, metalake, "allowed", List.of(roleId), List.of("role"));
+ putUser(store, metalake, "denied", List.of(), List.of());
+ putUser(store, metalake, "tagOnly", List.of(tagOnlyRoleId), List.of("tagOnly"));
+ putUser(store, metalake, "metalakeOwner", List.of(), List.of());
+ putUser(store, metalake, "groupUser", List.of(), List.of());
+ putUser(store, metalake, "deniedTag", List.of(roleId, denyRoleId), List.of("role", "denyTag"));
+ putGroup(store, metalake, "taggers", List.of(roleId), List.of("role"));
+ putUser(store, metalake, "governor", List.of(governanceRoleId), List.of("governanceRole"));
+ putUser(store, metalake, "labelColumn", List.of(labelRoleId), List.of("labelColumn"));
+ setOwner(metalake, NameIdentifier.of(metalake), Entity.EntityType.METALAKE, "metalakeOwner");
+ setOwner(
+ metalake, NameIdentifierUtil.ofTag(metalake, "label"), Entity.EntityType.TAG, "governor");
+ GravitinoEnv env = GravitinoEnv.getInstance();
+ try (EnvOverride overrides =
+ new EnvOverride(
+ "config",
+ "entityStore",
+ "gravitinoAuthorizer",
+ "policyDispatcher",
+ "tagDispatcher",
+ "internalTagDispatcher",
+ "internalCatalogDispatcher",
+ "internalSchemaDispatcher",
+ "internalTableDispatcher",
+ "catalogManager",
+ "eventBus");
+ JcasbinAuthorizer authorizer = new JcasbinAuthorizer();
+ MockedStatic<PrincipalUtils> principals = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class)) {
+ overrides
+ .set("config", config)
+ .set("entityStore", store)
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("eventBus", mock(EventBus.class))
+ .set("internalCatalogDispatcher", existingCatalogs());
+ SchemaDispatcher schemas = mock(SchemaDispatcher.class);
+ when(schemas.schemaExists(any())).thenReturn(true);
+ overrides.set("internalSchemaDispatcher", schemas);
+ TableDispatcher tables = mock(TableDispatcher.class);
+ when(tables.tableExists(any())).thenReturn(true);
+ overrides.set("internalTableDispatcher", tables);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ overrides.set("catalogManager", catalogManagerFor(catalog));
+ AtomicReference<UserPrincipal> current = new AtomicReference<>(new UserPrincipal("allowed"));
+ principals.when(PrincipalUtils::getCurrentPrincipal).thenAnswer(i -> current.get());
+ principals.when(PrincipalUtils::getCurrentUserName).thenAnswer(i -> current.get().getName());
+ principals.when(() -> PrincipalUtils.doAs(any(), any())).thenCallRealMethod();
+ tags.addPolicyForTag(metalake, "visible", "policy", AllValuesSelector.get());
+ authorizer.initialize();
+ env.setGravitinoAuthorizer(authorizer);
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ TagsAssociateRequest add = new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ Response allow =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", add},
+ i -> operations.associateTagsForObject(metalake, "catalog", "catalog", add)));
+ assertEquals(200, allow.getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("denied"));
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ TagsAssociateRequest remove =
+ new TagsAssociateRequest(new String[0], new String[] {"visible"});
+ Response deny =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "catalog", "catalog", remove},
+ i -> operations.associateTagsForObject(metalake, "catalog", "catalog", remove)));
+ assertEquals(403, deny.getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ TagOperations legacy = withHttpRequest(new TagOperations(tags));
+ Object[] resources = {operations, operations, legacy};
+ String[] methods = {
+ "associateTagsForObject", "associateTagValuesForObject", "associateTagsForObject"
+ };
+ for (int route = 0; route < resources.length; route++) {
+ Object resource = resources[route];
+ String name = methods[route];
+ Object routeAdd = visibleTagRequest(route == 1, true);
+ Object routeRemove = visibleTagRequest(route == 1, false);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(200, invokeRealTagRoute(resource, name, metalake, routeRemove).getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(200, invokeRealTagRoute(resource, name, metalake, routeAdd).getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(
+ new UserPrincipal("groupUser", List.of(new UserGroup(Optional.empty(), "taggers"))));
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ assertEquals(200, invokeRealTagRoute(resource, name, metalake, routeRemove).getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(200, invokeRealTagRoute(resource, name, metalake, routeAdd).getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("deniedTag"));
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ assertEquals(403, invokeRealTagRoute(resource, name, metalake, routeRemove).getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("denied"));
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ assertEquals(403, invokeRealTagRoute(resource, name, metalake, routeRemove).getStatus());
+ Object missing =
+ route == 1
+ ? new TagValuesAssociateRequest(
+ new TagValue[] {TagValue.noValue("missing")}, new TagValue[0])
+ : new TagsAssociateRequest(new String[] {"missing"}, new String[0]);
+ assertEquals(403, invokeRealTagRoute(resource, name, metalake, missing).getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed").withActiveRoles(ActiveRoles.none()));
+ assertTrue(authorizer.isMetalakeUser(metalake, new AuthorizationRequestContext()));
+ assertEquals(403, invokeRealTagRoute(resource, name, metalake, routeRemove).getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ }
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ add)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("denied"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("tagOnly"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("deniedTag"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("labelColumn"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ new TagsAssociateRequest(new String[] {"label"}, new String[0]))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "label").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ new TagsAssociateRequest(new String[0], new String[] {"label"}))
+ .getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "label").length);
+ for (int route = 0; route < resources.length; route++) {
+ Object resource = resources[route];
+ String name = methods[route];
+ Object routeAdd = visibleTagRequest(route == 1, true);
+ Object routeRemove = visibleTagRequest(route == 1, false);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(resource, name, metalake, "table", "catalog.schema.table", routeAdd)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("deniedTag"));
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ resource, name, metalake, "table", "catalog.schema.table", routeRemove)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ resource, name, metalake, "table", "catalog.schema.table", routeRemove)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ Response inherited =
+ operations.getTagForObject(metalake, "table", "catalog.schema.table", "visible");
+ assertEquals(200, inherited.getStatus());
+ assertTrue(((TagResponse) inherited.getEntity()).getTag().inherited().orElse(false));
+ }
+ current.set(new UserPrincipal("allowed"));
+ TagsAssociateRequest nestedAdd =
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ TagsAssociateRequest nestedRemove =
+ new TagsAssociateRequest(new String[0], new String[] {"visible"});
+ Capability quoteAware =
+ new Capability() {
+ @Override
+ public CapabilityResult caseSensitiveOnName(Scope scope) {
+ return CapabilityResult.unsupported("normalization depends on quoting");
+ }
+
+ @Override
+ public String normalizeName(Scope scope, String name) {
+ if (name.startsWith("\"") && name.endsWith("\"") && name.length() >= 2) {
+ return name.substring(1, name.length() - 1);
+ }
+ return name;
+ }
+ };
+ when(catalog.capability()).thenReturn(quoteAware);
+ ThrowingRunnable mixedCaseAncestorsChecked =
+ () -> {
+ Map<NameIdentifier, Optional<NamespacedEntityId>> ancestors =
+ TagAssignmentAuthorization.checkedSchemaAncestors();
+ assertEquals(
+ List.of(NameIdentifier.of(metalake, "catalog", "MiXeD")),
+ List.copyOf(ancestors.keySet()));
+ assertTrue(ancestors.values().stream().allMatch(Optional::isPresent));
+ };
+ String mixedCaseTable = "catalog.\"MiXeD\".\"MiXeDTbl\"";
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "table",
+ mixedCaseTable,
+ nestedAdd,
+ mixedCaseAncestorsChecked)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "table",
+ mixedCaseTable,
+ nestedRemove,
+ mixedCaseAncestorsChecked)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ ThrowingRunnable nestedAncestorsChecked =
+ () -> {
+ Map<NameIdentifier, Optional<NamespacedEntityId>> ancestors =
+ TagAssignmentAuthorization.checkedSchemaAncestors();
+ assertEquals(
+ List.of(
+ NameIdentifier.of(metalake, "catalog", "outer"),
+ NameIdentifier.of(metalake, "catalog", "outer:inner")),
+ List.copyOf(ancestors.keySet()));
+ assertTrue(ancestors.values().stream().allMatch(Optional::isPresent));
+ };
+ String nestedTable = "catalog.outer:inner.nested_table";
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "table",
+ nestedTable,
+ nestedAdd,
+ nestedAncestorsChecked)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "table",
+ nestedTable,
+ nestedRemove,
+ nestedAncestorsChecked)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "schema",
+ "catalog.outer:inner",
+ nestedAdd)
+ .getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "schema",
+ "catalog.outer:inner",
+ nestedRemove)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 400,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[] {"visible", ""}, new String[0]))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("metalakeOwner"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[] {"label"}, new String[] {"missing"}))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "label").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[0], new String[] {"label"}))
+ .getStatus());
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ add)
+ .getStatus());
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ "column",
+ "catalog.schema.coltable.c1",
+ remove)
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ current.set(new UserPrincipal("allowed"));
+ assertEquals(
+ 404,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(
+ new String[] {HiddenPolicyTag.name(policy.id())}, new String[0]))
+ .getStatus());
+ assertEquals(
+ 403,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[] {"foreign_tag"}, new String[0]))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(0, tags.listMetadataObjectsForTag(foreignMetalake, "foreign_tag").length);
+ PassThroughAuthorizer disabledAuthorizer = new PassThroughAuthorizer();
+ config.set(Configs.ENABLE_AUTHORIZATION, false);
+ env.setGravitinoAuthorizer(disabledAuthorizer);
+ when(provider.getGravitinoAuthorizer()).thenReturn(disabledAuthorizer);
+ current.set(new UserPrincipal("denied"));
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[0], new String[] {"visible"}))
+ .getStatus());
+ assertEquals(0, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[0], new String[] {"label"}))
+ .getStatus());
+ assertEquals(
+ 200,
+ invokeRealTagRoute(
+ operations,
+ "associateTagsForObject",
+ metalake,
+ new TagsAssociateRequest(new String[] {"label"}, new String[] {"missing"}))
+ .getStatus());
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "label").length);
+ }
+ }
+
+ @TestTemplate
+ void testColdExternalTableCanBeTaggedByMetalakeOwner() throws Throwable {
+ String metalake = "cold_table_auth_h2";
+ createAndInsertMakeLake(metalake);
+ createAndInsertCatalog(metalake, "catalog");
+ createAndInsertSchema(metalake, "catalog", "schema");
+ createAndInsertTagEntity("visible", "", metalake);
+ RelationalEntityStore store = newStore();
+ PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
+ TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ UserPrincipal principal = new UserPrincipal("tester");
+ try (EnvOverride overrides = new EnvOverride();
+ MockedSecurity security = new MockedSecurity(principal)) {
+ overrides
+ .setPolicyAndTagDispatchers(policies, tags)
+ .set("entityStore", store)
+ .set("eventBus", mock(EventBus.class));
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(Capability.DEFAULT);
+ overrides.set("catalogManager", catalogManagerFor(catalog));
+ TableDispatcher tables = mock(TableDispatcher.class);
+ when(tables.tableExists(any()))
+ .thenAnswer(
+ invocation -> {
+ NameIdentifier name = invocation.getArgument(0);
+ String schema = name.namespace().level(2);
+ if ("new_schema".equals(schema)) {
+ createAndInsertSchema(metalake, "catalog", schema);
+ }
+ createAndInsertTableEntity(Namespace.of(metalake, "catalog", schema), name.name());
+ return true;
+ });
+ overrides.set("internalTableDispatcher", tables);
+ GravitinoAuthorizer authorizer = security.mockAuthorizer(MetadataObject.Type.METALAKE);
+ TagsAssociateRequest request =
+ new TagsAssociateRequest(new String[] {"visible"}, new String[0]);
+ MetadataObjectTagOperations operations =
+ withHttpRequest(new MetadataObjectTagOperations(tags));
+ Method method = associateTagsMethod();
+ Response response =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "table", "catalog.schema.table", request},
+ ignored ->
+ operations.associateTagsForObject(
+ metalake, "table", "catalog.schema.table", request)));
+ assertTrue(
+ store.exists(
+ NameIdentifier.of(metalake, "catalog", "schema", "table"), Entity.EntityType.TABLE));
+ assertEquals(
+ 200,
+ response.getStatus(),
+ "a cold external table should be taggable by the metalake owner");
+ assertEquals(1, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ doAnswer(ownerOf(MetadataObject.Type.CATALOG, MetadataObject.Type.TAG))
+ .when(authorizer)
+ .isOwner(any(), any(), any(), any());
+ Response catalogOwnerResponse =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "table", "catalog.schema.table2", request},
+ ignored ->
+ operations.associateTagsForObject(
+ metalake, "table", "catalog.schema.table2", request)));
+ assertEquals(200, catalogOwnerResponse.getStatus());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ putPolicy(store, metalake, "access", Policy.BuiltInType.ACCESS_CONTROL, selectContent());
+ tags.addPolicyForTag(metalake, "visible", "access", AllValuesSelector.get());
+ assertEquals(2, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ when(authorizer.authorize(any(), any(), any(), eq(Privilege.Name.APPLY_TAG), any()))
+ .thenReturn(true);
+ when(authorizer.hasMetadataPrivilegePermission(any(), any(), any(), any())).thenReturn(true);
+ Response accessTagResponse =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "table", "catalog.schema.table3", request},
+ ignored ->
+ operations.associateTagsForObject(
+ metalake, "table", "catalog.schema.table3", request)));
+ assertEquals(200, accessTagResponse.getStatus());
+ assertEquals(3, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ Response coldSchemaResponse =
+ intercept(
+ method,
+ invocation(
+ method,
+ new Object[] {metalake, "table", "catalog.new_schema.table4", request},
+ ignored ->
+ operations.associateTagsForObject(
+ metalake, "table", "catalog.new_schema.table4", request)));
+ assertEquals(200, coldSchemaResponse.getStatus());
+ assertEquals(4, tags.listMetadataObjectsForTag(metalake, "visible").length);
+ }
+ }
+
+ private RelationalEntityStore newStore() throws IllegalAccessException {
+ RelationalEntityStore store = new RelationalEntityStore();
+ wireStore(store, new Config(false) {});
+ return store;
+ }
+
+ private void wireStore(RelationalEntityStore store, Config config) throws IllegalAccessException {
+ FieldUtils.writeField(store, "backend", backend, true);
+ FieldUtils.writeField(store, "cache", new NoOpsCache(config), true);
+ }
+
+ private static PolicyContent selectContent() {
+ return PolicyContents.accessControl(List.of(Privilege.Name.SELECT_TABLE), List.of("reader"));
+ }
+
+ private static PolicyEntity newPolicy(
+ String metalake, String name, Policy.BuiltInType type, PolicyContent content) {
+ return PolicyEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withNamespace(Namespace.of(metalake))
+ .withName(name)
+ .withPolicyType(type)
+ .withEnabled(false)
+ .withContent(content)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
+ private static PolicyEntity putPolicy(
+ RelationalEntityStore store,
+ String metalake,
+ String name,
+ Policy.BuiltInType type,
+ PolicyContent content)
+ throws IOException {
+ PolicyEntity policy = newPolicy(metalake, name, type, content);
+ store.put(policy, false);
+ return policy;
+ }
+
+ private static long putRole(
+ RelationalEntityStore store, String metalake, String name, List<SecurableObject> objects)
+ throws IOException {
+ long id = RandomIdGenerator.INSTANCE.nextId();
+ store.put(
+ RoleEntity.builder()
+ .withId(id)
+ .withName(name)
+ .withNamespace(AuthorizationUtils.ofRoleNamespace(metalake))
+ .withProperties(null)
+ .withSecurableObjects(objects)
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ return id;
+ }
+
+ private static void putUser(
+ RelationalEntityStore store,
+ String metalake,
+ String name,
+ List<Long> roleIds,
+ List<String> roleNames)
+ throws IOException {
+ store.put(
+ UserEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(AuthorizationUtils.ofUserNamespace(metalake))
+ .withRoleIds(roleIds)
+ .withRoleNames(roleNames)
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ }
+
+ private static void putGroup(
+ RelationalEntityStore store,
+ String metalake,
+ String name,
+ List<Long> roleIds,
+ List<String> roleNames)
+ throws IOException {
+ store.put(
+ GroupEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(AuthorizationUtils.ofGroupNamespace(metalake))
+ .withRoleIds(roleIds)
+ .withRoleNames(roleNames)
+ .withAuditInfo(AUDIT_INFO)
+ .build(),
+ false);
+ }
+
+ private static void setOwner(
+ String metalake, NameIdentifier entity, Entity.EntityType type, String user) {
+ OwnerMetaService.getInstance()
+ .setOwner(entity, type, NameIdentifierUtil.ofUser(metalake, user), Entity.EntityType.USER);
+ }
+
+ private static CatalogDispatcher existingCatalogs() {
+ CatalogDispatcher catalogs = mock(CatalogDispatcher.class);
+ when(catalogs.catalogExists(any())).thenReturn(true);
+ return catalogs;
+ }
+
+ private static CatalogManager catalogManagerFor(BaseCatalog<?> catalog) throws Exception {
+ CatalogManager catalogManager = mock(CatalogManager.class);
+ doAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog<?>, Object> operation = invocation.getArgument(1);
+ return operation.apply(catalog);
+ })
+ .when(catalogManager)
+ .doWithCatalog(any(), any());
+ return catalogManager;
+ }
+
+ private static Answer<Boolean> ownerOf(MetadataObject.Type... ownedTypes) {
+ List<MetadataObject.Type> owned = List.of(ownedTypes);
+ return invocation -> owned.contains(((MetadataObject) invocation.getArgument(2)).type());
+ }
+
+ private static <T> T withHttpRequest(T resource) throws IllegalAccessException {
+ FieldUtils.writeField(resource, "httpRequest", mock(HttpServletRequest.class), true);
+ return resource;
+ }
+
+ private static Method associateTagsMethod() throws NoSuchMethodException {
+ return MetadataObjectTagOperations.class.getMethod(
+ "associateTagsForObject",
+ String.class,
+ String.class,
+ String.class,
+ TagsAssociateRequest.class);
+ }
+
+ private static MethodInvocation invocation(Method method, Object[] arguments) {
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments()).thenReturn(arguments);
+ return invocation;
+ }
+
+ private static MethodInvocation invocation(Method method, Object[] arguments, Answer<?> proceed)
+ throws Throwable {
+ MethodInvocation invocation = invocation(method, arguments);
+ when(invocation.proceed()).thenAnswer(proceed);
+ return invocation;
+ }
+
+ private static Response intercept(Method method, MethodInvocation invocation) throws Throwable {
+ return (Response)
+ new GravitinoInterceptionService().getMethodInterceptors(method).get(0).invoke(invocation);
+ }
+
+ private static Object visibleTagRequest(boolean tagValues, boolean add) {
+ if (tagValues) {
+ TagValue[] visible = {TagValue.noValue("visible")};
+ return add
+ ? new TagValuesAssociateRequest(visible, new TagValue[0])
+ : new TagValuesAssociateRequest(new TagValue[0], visible);
+ }
+ String[] visible = {"visible"};
+ return add
+ ? new TagsAssociateRequest(visible, new String[0])
+ : new TagsAssociateRequest(new String[0], visible);
+ }
+
+ private static Response invokeRealTagRoute(
+ Object resource, String name, String metalake, Object request) throws Throwable {
+ return invokeRealTagRoute(resource, name, metalake, "catalog", "catalog", request);
+ }
+
+ private static Response invokeRealTagRoute(
+ Object resource, String name, String metalake, String type, String fullName, Object request)
+ throws Throwable {
+ return invokeRealTagRoute(resource, name, metalake, type, fullName, request, () -> {});
+ }
+
+ private static Response invokeRealTagRoute(
+ Object resource,
+ String name,
+ String metalake,
+ String type,
+ String fullName,
+ Object request,
+ ThrowingRunnable beforeProceed)
+ throws Throwable {
+ Method method =
+ resource
+ .getClass()
+ .getMethod(name, String.class, String.class, String.class, request.getClass());
+ MethodInvocation invocation =
+ invocation(
+ method,
+ new Object[] {metalake, type, fullName, request},
+ i -> {
+ beforeProceed.run();
+ return method.invoke(resource, metalake, type, fullName, request);
+ });
+ return intercept(method, invocation);
+ }
+
+ private static void runAsSecondWriter(UserPrincipal principal, ThrowingRunnable action)
+ throws Exception {
+ ExecutorService writer = Executors.newSingleThreadExecutor();
+ try {
+ writer
+ .submit(
+ () -> {
+ try (MockedStatic<PrincipalUtils> writerPrincipal =
+ mockStatic(PrincipalUtils.class)) {
+ writerPrincipal.when(PrincipalUtils::getCurrentPrincipal).thenReturn(principal);
+ writerPrincipal
+ .when(PrincipalUtils::getCurrentUserName)
+ .thenReturn(principal.getName());
+ action.run();
+ }
+ return null;
+ })
+ .get(10, TimeUnit.SECONDS);
+ } finally {
+ writer.shutdownNow();
+ }
+ }
+
+ private boolean hasVisibleBinding(PolicyManager manager, String metalake, String policy) {
+ return Arrays.stream(manager.listTagAssociationsForPolicy(metalake, policy))
+ .anyMatch(relation -> relation.targetEntity().name().equals("visible"));
+ }
+
+ @FunctionalInterface
+ private interface ThrowingRunnable {
+ void run() throws Exception;
+ }
+
+ /** Overrides {@link GravitinoEnv} fields and restores their original values on close. */
+ private static final class EnvOverride implements AutoCloseable {
+ private final GravitinoEnv env = GravitinoEnv.getInstance();
+ private final Map<String, Object> originals = new LinkedHashMap<>();
+
+ private EnvOverride(String... preservedFields) throws IllegalAccessException {
+ for (String field : preservedFields) {
+ preserve(field);
+ }
+ }
+
+ private EnvOverride set(String field, Object value) throws IllegalAccessException {
+ preserve(field);
+ FieldUtils.writeField(env, field, value, true);
+ return this;
+ }
+
+ private EnvOverride setPolicyAndTagDispatchers(PolicyManager policies, TagManager tags)
+ throws IllegalAccessException {
+ return set("policyDispatcher", policies)
+ .set("tagDispatcher", tags)
+ .set("internalTagDispatcher", tags);
+ }
+
+ @Override
+ public void close() throws IllegalAccessException {
+ for (Map.Entry<String, Object> original : originals.entrySet()) {
+ FieldUtils.writeField(env, original.getKey(), original.getValue(), true);
+ }
+ }
+
+ private void preserve(String field) throws IllegalAccessException {
+ if (!originals.containsKey(field)) {
+ originals.put(field, FieldUtils.readField(env, field, true));
+ }
+ }
+ }
+
+ /**
+ * Statically mocks the current principal, the authorizer provider, and the current-user check.
+ */
+ private static final class MockedSecurity implements AutoCloseable {
+ private final MockedStatic<PrincipalUtils> principals = mockStatic(PrincipalUtils.class);
+ private final MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ private final MockedStatic<AuthorizationUtils> auth = mockStatic(AuthorizationUtils.class);
+
+ private MockedSecurity(UserPrincipal principal) {
+ principals.when(PrincipalUtils::getCurrentPrincipal).thenReturn(principal);
+ principals.when(PrincipalUtils::getCurrentUserName).thenReturn(principal.getName());
+ principals.when(() -> PrincipalUtils.doAs(any(), any())).thenCallRealMethod();
+ }
+
+ private GravitinoAuthorizer mockAuthorizer(MetadataObject.Type... ownedTypes) {
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+ when(authorizer.isOwner(any(), any(), any(), any())).thenAnswer(ownerOf(ownedTypes));
+ auth.when(() -> AuthorizationUtils.checkCurrentUser(any(), any(), any()))
+ .thenAnswer(invocation -> null);
+ return authorizer;
+ }
+
+ @Override
+ public void close() {
+ auth.close();
+ providers.close();
+ principals.close();
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestAssociateTagAuthorizationExecutor.java b/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestAssociateTagAuthorizationExecutor.java
index 184b29ad1c..2c90d766e5 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestAssociateTagAuthorizationExecutor.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestAssociateTagAuthorizationExecutor.java
@@ -19,37 +19,216 @@
package org.apache.gravitino.server.web.filter.authorization;
+import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
+import java.security.Principal;
import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationalEntity;
+import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.dto.requests.TagValuesAssociateRequest;
import org.apache.gravitino.dto.requests.TagsAssociateRequest;
import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.TagValueSelector;
+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.authorization.PassThroughAuthorizer;
import org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.NameIdentifierUtil;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
public class TestAssociateTagAuthorizationExecutor {
+ @Test
+ void testAuthorizationDisabledDoesNotReadPolicies() throws Exception {
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ when(provider.getGravitinoAuthorizer()).thenReturn(new PassThroughAuthorizer());
+ try (MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class)) {
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ TagsAssociateRequest request = new TagsAssociateRequest(new String[] {"access"}, null);
+ Method method = TestOperations.class.getDeclaredMethod("associateV1", request.getClass());
+ AssociateTagAuthorizationExecutor executor =
+ new AssociateTagAuthorizationExecutor(
+ "METALAKE::OWNER",
+ method.getParameters(),
+ new Object[] {request},
+ Map.of(Entity.EntityType.METALAKE, NameIdentifier.of("metalake")),
+ Collections.emptyMap(),
+ Optional.empty());
+ executor.accessTagClassifier =
+ (metalake, tag) -> {
+ throw new IllegalStateException("unexpected read");
+ };
+ assertTrue(executor.execute(new AuthorizationRequestContext()));
+ }
+ }
+
+ @Test
+ void testClassificationFailureStopsAuthorization() throws Exception {
+ AssociateTagAuthorizationExecutor executor =
+ enabledExecutor("associateV1", new TagsAssociateRequest(new String[] {"access"}, null));
+ executor.accessTagClassifier =
+ (metalake, tag) -> {
+ throw new IllegalStateException("unavailable");
+ };
+ assertThrows(
+ IllegalStateException.class, () -> executor.execute(new AuthorizationRequestContext()));
+ }
+
+ @Test
+ void testAccessExpressionRequiresTagGrantAndObjectAuthority() {
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ AuthorizationExpressionEvaluator evaluator =
+ new AuthorizationExpressionEvaluator(APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION, authorizer);
+ Map<Entity.EntityType, NameIdentifier> metadata =
+ Map.of(
+ Entity.EntityType.METALAKE,
+ NameIdentifier.of("lake"),
+ Entity.EntityType.TAG,
+ NameIdentifierUtil.ofTag("lake", "sensitive"));
+ Map<String, Object> path =
+ Map.of("p_metalake", "lake", "p_type", "TABLE", "p_fullName", "c.s.t");
+ when(authorizer.authorize(
+ nullable(Principal.class), any(), any(), eq(Privilege.Name.APPLY_TAG), any()))
+ .thenReturn(true);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ when(authorizer.hasMetadataPrivilegePermission(any(), any(), any(), any())).thenReturn(true);
+ assertTrue(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ when(authorizer.deny(
+ nullable(Principal.class), any(), any(), eq(Privilege.Name.APPLY_TAG), any()))
+ .thenReturn(true);
+ assertFalse(
+ evaluator.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ AuthorizationExpressionEvaluator disabled =
+ new AuthorizationExpressionEvaluator(
+ APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION, new PassThroughAuthorizer());
+ assertTrue(
+ disabled.evaluate(metadata, path, new AuthorizationRequestContext(), Optional.empty()));
+ }
+
+ @Test
+ void testPolicyClassification() {
+ PolicyEntity access = mock(PolicyEntity.class);
+ PolicyEntity governance = mock(PolicyEntity.class);
+ when(access.policyType()).thenReturn(Policy.BuiltInType.ACCESS_CONTROL);
+ when(governance.policyType()).thenReturn(Policy.BuiltInType.CUSTOM);
+ RelationalEntity<?> accessRelation = mock(RelationalEntity.class);
+ RelationalEntity<?> governanceRelation = mock(RelationalEntity.class);
+ doReturn(access).when(accessRelation).targetEntity();
+ doReturn(governance).when(governanceRelation).targetEntity();
+
+ assertFalse(AssociateTagAuthorizationExecutor.isAccessTag(new RelationalEntity<?>[0]));
+ assertFalse(
+ AssociateTagAuthorizationExecutor.isAccessTag(
+ new RelationalEntity<?>[] {governanceRelation}));
+ assertTrue(
+ AssociateTagAuthorizationExecutor.isAccessTag(
+ new RelationalEntity<?>[] {governanceRelation, accessRelation}));
+ RelationalEntity<PolicyEntity> disabledWithSelector =
+ new RelationalEntity<>(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ NameIdentifierUtil.ofTag("lake", "sensitive"),
+ Entity.EntityType.TAG,
+ access,
+ PolicyAssociationSelectorSerde.serialize(TagValueSelector.of("finance")));
+ assertFalse(access.enabled());
+ assertTrue(
+ AssociateTagAuthorizationExecutor.isAccessTag(
+ new RelationalEntity<?>[] {disabledWithSelector}));
+ }
+
+ @Test
+ void testAccessTagUsesStrongerAuthorization() throws Exception {
+ AssociateTagAuthorizationExecutor executor =
+ enabledExecutor("associateV1", new TagsAssociateRequest(new String[] {"access"}, null));
+ executor.accessTagClassifier = (metalake, tag) -> true;
+ AuthorizationExpressionEvaluator evaluator = mock(AuthorizationExpressionEvaluator.class);
+ executor.accessTagEvaluator = evaluator;
+ when(evaluator.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(false);
+ AuthorizationRequestContext context = new AuthorizationRequestContext();
+ assertFalse(executor.execute(context));
+ assertEquals(
+ APPLY_ACCESS_TAG_AUTHORIZATION_EXPRESSION, context.getOriginalAuthorizationExpression());
+ verify(evaluator).evaluate(anyMap(), anyMap(), any(), any());
+ }
+
+ @Test
+ void testMixedBatchIsRejectedWhenAccessTagIsDenied() throws Exception {
+ AssociateTagAuthorizationExecutor executor =
+ enabledExecutor(
+ "associateV1", new TagsAssociateRequest(new String[] {"descriptive", "access"}, null));
+ executor.accessTagClassifier = (metalake, tag) -> tag.equals("access");
+ AuthorizationExpressionEvaluator ordinary = mock(AuthorizationExpressionEvaluator.class);
+ AuthorizationExpressionEvaluator access = mock(AuthorizationExpressionEvaluator.class);
+ executor.authorizationExpressionEvaluator = ordinary;
+ executor.accessTagEvaluator = access;
+ when(ordinary.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(true);
+ when(access.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(false);
+ assertFalse(executor.execute(new AuthorizationRequestContext()));
+ verify(ordinary).evaluate(anyMap(), anyMap(), any(), any());
+ verify(access).evaluate(anyMap(), anyMap(), any(), any());
+ }
+
+ @Test
+ void testDisabledPolicyWithNonmatchingSelectorStillProtectsValue() throws Exception {
+ PolicyEntity access = mock(PolicyEntity.class);
+ when(access.policyType()).thenReturn(Policy.BuiltInType.ACCESS_CONTROL);
+ RelationalEntity<PolicyEntity> relation =
+ new RelationalEntity<>(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ NameIdentifierUtil.ofTag("metalake", "sensitive"),
+ Entity.EntityType.TAG,
+ access,
+ PolicyAssociationSelectorSerde.serialize(TagValueSelector.of("finance")));
+ AssociateTagAuthorizationExecutor executor =
+ enabledExecutor(
+ "associateV2",
+ new TagValuesAssociateRequest(new TagValue[] {TagValue.of("sensitive", "risk")}, null));
+ executor.accessTagClassifier =
+ (metalake, tag) ->
+ AssociateTagAuthorizationExecutor.isAccessTag(new RelationalEntity<?>[] {relation});
+ AuthorizationExpressionEvaluator evaluator = mock(AuthorizationExpressionEvaluator.class);
+ executor.accessTagEvaluator = evaluator;
+ when(evaluator.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(false);
+ assertFalse(access.enabled());
+ assertFalse(executor.execute(new AuthorizationRequestContext()));
+ verify(evaluator).evaluate(anyMap(), anyMap(), any(), any());
+ }
+
@Test
public void testAuthorizesV1TagNames() throws Exception {
TagsAssociateRequest request =
new TagsAssociateRequest(new String[] {"pii"}, new String[] {"data_domain"});
- assertAuthorizesAllTags("associateV1", TagsAssociateRequest.class, request);
+ assertAuthorizesAllTags("associateV1", request);
}
@Test
@@ -58,58 +237,48 @@ public class TestAssociateTagAuthorizationExecutor {
new TagValuesAssociateRequest(
new TagValue[] {TagValue.noValue("pii")},
new TagValue[] {TagValue.of("data_domain", "finance")});
- assertAuthorizesAllTags("associateV2", TagValuesAssociateRequest.class, request);
+ assertAuthorizesAllTags("associateV2", request);
}
@Test
- public void testAuthorizesV2TagNamesWithoutValidatingValues() throws Exception {
+ void testInvalidV2ValuesSkipClassification() throws Exception {
TagValuesAssociateRequest request =
JsonUtils.objectMapper()
.readValue(
"{\"tagsToAdd\":[{\"name\":\"data_domain\",\"value\":\" \"}]}",
TagValuesAssociateRequest.class);
- Method method = TestOperations.class.getDeclaredMethod("associateV2", request.getClass());
- Map<Entity.EntityType, NameIdentifier> metadataContext = new HashMap<>();
- metadataContext.put(Entity.EntityType.METALAKE, NameIdentifier.of("metalake"));
- AssociateTagAuthorizationExecutor executor =
- new AssociateTagAuthorizationExecutor(
- "TAG::OWNER",
- method.getParameters(),
- new Object[] {request},
- metadataContext,
- Collections.emptyMap(),
- Optional.empty());
+ assertAuthorizesAllTags("associateV2", request, 1);
+ }
+
+ private static void assertAuthorizesAllTags(String methodName, Object request) throws Exception {
+ assertAuthorizesAllTags(methodName, request, 2);
+ }
+ private static void assertAuthorizesAllTags(
+ String methodName, Object request, int expectedEvaluations) throws Exception {
+ AssociateTagAuthorizationExecutor executor = enabledExecutor(methodName, request);
AuthorizationExpressionEvaluator evaluator = mock(AuthorizationExpressionEvaluator.class);
- AuthorizationRequestContext context = new AuthorizationRequestContext();
when(evaluator.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(true);
executor.authorizationExpressionEvaluator = evaluator;
+ executor.accessTagClassifier = (metalake, tag) -> false;
- assertTrue(executor.execute(context));
- verify(evaluator, times(1)).evaluate(anyMap(), anyMap(), any(), any());
+ assertTrue(executor.execute(new AuthorizationRequestContext()));
+ verify(evaluator, times(expectedEvaluations)).evaluate(anyMap(), anyMap(), any(), any());
}
- private static void assertAuthorizesAllTags(
- String methodName, Class<?> requestType, Object request) throws Exception {
- Method method = TestOperations.class.getDeclaredMethod(methodName, requestType);
- Map<Entity.EntityType, NameIdentifier> metadataContext = new HashMap<>();
- metadataContext.put(Entity.EntityType.METALAKE, NameIdentifier.of("metalake"));
+ private static AssociateTagAuthorizationExecutor enabledExecutor(
+ String methodName, Object request) throws Exception {
+ Method method = TestOperations.class.getDeclaredMethod(methodName, request.getClass());
AssociateTagAuthorizationExecutor executor =
new AssociateTagAuthorizationExecutor(
"TAG::OWNER",
method.getParameters(),
new Object[] {request},
- metadataContext,
+ Map.of(Entity.EntityType.METALAKE, NameIdentifier.of("metalake")),
Collections.emptyMap(),
Optional.empty());
-
- AuthorizationExpressionEvaluator evaluator = mock(AuthorizationExpressionEvaluator.class);
- AuthorizationRequestContext context = new AuthorizationRequestContext();
- when(evaluator.evaluate(anyMap(), anyMap(), any(), any())).thenReturn(true);
- executor.authorizationExpressionEvaluator = evaluator;
-
- assertTrue(executor.execute(context));
- verify(evaluator, times(2)).evaluate(anyMap(), anyMap(), any(), any());
+ executor.authorizationDisabled = false;
+ return executor;
}
private static class TestOperations {