Skip to content

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

[#13909][#13910] feat: add tag-based access policy resolution and matching (#14364)

Abhijeet Singh1dcedde7f39d
diff --git a/common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java b/common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java
index 266cdda849..80de4f11f7 100644
--- a/common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java
+++ b/common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java
@@ -65,14 +65,19 @@ public final class PolicyAssociationSelectorSerde {
}
/**
- * Deserializes a selector.
+ * Deserializes a non-null selector.
*
* @param json The selector JSON.
* @return The selector.
+ * @throws IllegalArgumentException If the JSON is invalid, unsupported, or represents null.
*/
public static PolicyAssociationSelector deserialize(String json) {
try {
- return MAPPER.readValue(json, PolicyAssociationSelector.class);
+ PolicyAssociationSelector selector = MAPPER.readValue(json, PolicyAssociationSelector.class);
+ if (selector == null) {
+ throw new IllegalArgumentException("Policy association selector cannot be JSON null");
+ }
+ return selector;
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Failed to deserialize policy association selector", e);
}
diff --git a/common/src/test/java/org/apache/gravitino/json/TestPolicyAssociationSelectorSerde.java b/common/src/test/java/org/apache/gravitino/json/TestPolicyAssociationSelectorSerde.java
index b071775205..c37575eca7 100644
--- a/common/src/test/java/org/apache/gravitino/json/TestPolicyAssociationSelectorSerde.java
+++ b/common/src/test/java/org/apache/gravitino/json/TestPolicyAssociationSelectorSerde.java
@@ -62,6 +62,8 @@ public class TestPolicyAssociationSelectorSerde {
@Test
void testRejectMissingRequiredFields() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> PolicyAssociationSelectorSerde.deserialize("null"));
Assertions.assertThrows(
IllegalArgumentException.class, () -> PolicyAssociationSelectorSerde.deserialize("{}"));
Assertions.assertThrows(
diff --git a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationRequestContext.java b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationRequestContext.java
index a7c139700f..e470ee1305 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationRequestContext.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationRequestContext.java
@@ -42,6 +42,8 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.auth.ActiveRoles;
import org.apache.gravitino.exceptions.NotFoundException;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.relational.po.auth.GroupUpdatedAt;
import org.apache.gravitino.storage.relational.po.auth.OwnerInfo;
import org.apache.gravitino.storage.relational.po.auth.RoleUpdatedAt;
@@ -97,6 +99,20 @@ public class AuthorizationRequestContext {
/** Per-request metadataId→owner cache. Deduplicates isOwner within a single request. */
private final Map<Long, Optional<OwnerInfo>> ownerCache = new ConcurrentHashMap<>();
+ /** Matched policies and read failures are retained only for the exact target in this request. */
+ private final Map<TagPolicyKey, CachedTagData<PolicyEntity>> tagPolicyCache =
+ new ConcurrentHashMap<>();
+
+ /** Direct assignments and read failures shared by targets with common ancestors. */
+ private final Map<TagPolicyKey, CachedTagData<TagEntity>> directTagCache =
+ new ConcurrentHashMap<>();
+
+ /** Caches whether each metalake has an enabled access-control policy during this HTTP request. */
+ private final Map<String, Boolean> enabledAccessPolicies = new ConcurrentHashMap<>();
+
+ /** Caches policy-existence lookup failures by metalake during this HTTP request. */
+ private final Map<String, RuntimeException> accessPolicyFailures = new ConcurrentHashMap<>();
+
/**
* Per-request roleId → {@link RoleUpdatedAt} map populated by the fat-JOIN prefetch on the
* authorize hot path. When present, {@code versionCheckAndLoadRoles} can skip its dedicated
@@ -336,10 +352,67 @@ public class AuthorizationRequestContext {
id -> Objects.requireNonNull(loader.apply(id), "Owner loader must not return null"));
}
+ /**
+ * Resolves tag-policy data at most once per target, independently of principal and privilege.
+ *
+ * @param metalake the containing metalake
+ * @param target the original canonical target, not an ancestor visited by the RBAC walk
+ * @param loader the resolver, returning a complete non-null list or throwing
+ * @return the immutable matched policies
+ * @throws RuntimeException if resolution fails
+ */
+ public List<PolicyEntity> computeTagPoliciesIfAbsent(
+ String metalake, MetadataObject target, Supplier<List<PolicyEntity>> loader) {
+ return tagPolicyCache
+ .computeIfAbsent(new TagPolicyKey(metalake, target), ignored -> new CachedTagData<>())
+ .get(loader);
+ }
+
+ /**
+ * Loads an object's direct tag assignments at most once across all targets in this request.
+ *
+ * @param metalake the containing metalake
+ * @param object the canonical object whose direct assignments are requested
+ * @param loader the reader, returning a complete non-null list or throwing
+ * @return the immutable direct assignments
+ * @throws RuntimeException if the read fails; the failure is retained for this request
+ */
+ public List<TagEntity> computeDirectTagsIfAbsent(
+ String metalake, MetadataObject object, Supplier<List<TagEntity>> loader) {
+ return directTagCache
+ .computeIfAbsent(new TagPolicyKey(metalake, object), ignored -> new CachedTagData<>())
+ .get(loader);
+ }
+
public String getOriginalAuthorizationExpression() {
return originalAuthorizationExpression;
}
+ /**
+ * Checks once per metalake and request whether any enabled access-control policy exists.
+ *
+ * <p>Privilege checks and list workers share the result, including {@code false}. A failed lookup
+ * is rethrown on subsequent calls; it is never treated as an absence of policies. A new request
+ * creates a new context and may retry the lookup.
+ *
+ * @param metalake the containing metalake
+ * @param loader the current policy-existence query
+ * @return whether the metalake contains an enabled access-control policy
+ * @throws RuntimeException if the query failed, including on subsequent calls in this request
+ */
+ public synchronized boolean hasEnabledAccessPolicies(String metalake, Supplier<Boolean> loader) {
+ if (accessPolicyFailures.containsKey(metalake)) {
+ throw accessPolicyFailures.get(metalake);
+ }
+ try {
+ return enabledAccessPolicies.computeIfAbsent(
+ metalake, ignored -> Objects.requireNonNull(loader.get()));
+ } catch (RuntimeException e) {
+ accessPolicyFailures.put(metalake, e);
+ throw e;
+ }
+ }
+
public void setOriginalAuthorizationExpression(String originalAuthorizationExpression) {
this.originalAuthorizationExpression = originalAuthorizationExpression;
}
@@ -462,4 +535,31 @@ public class AuthorizationRequestContext {
private static class CatalogNormalizationState {
@Nullable private RuntimeException failure;
}
+
+ @AllArgsConstructor
+ @EqualsAndHashCode
+ private static class TagPolicyKey {
+ private final String metalake;
+ private final MetadataObject target;
+ }
+
+ private static class CachedTagData<T> {
+ @Nullable private List<T> values;
+ @Nullable private RuntimeException failure;
+
+ private synchronized List<T> get(Supplier<List<T>> loader) {
+ if (failure != null) {
+ throw failure;
+ }
+ if (values == null) {
+ try {
+ values = List.copyOf(loader.get());
+ } catch (RuntimeException e) {
+ failure = e;
+ throw e;
+ }
+ }
+ return values;
+ }
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/authorization/TagPolicyMatcher.java b/core/src/main/java/org/apache/gravitino/authorization/TagPolicyMatcher.java
new file mode 100644
index 0000000000..35407356f7
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/authorization/TagPolicyMatcher.java
@@ -0,0 +1,66 @@
+/*
+ * 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.authorization;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.policy.AccessControlContent;
+import org.apache.gravitino.policy.Policy;
+
+/**
+ * Matches requested privileges and active roles against policies matched by the object resolver.
+ */
+public final class TagPolicyMatcher {
+ private TagPolicyMatcher() {}
+
+ /**
+ * Finds the first policy that confers a privilege on an effective active role.
+ *
+ * @param privilege the requested privilege
+ * @param activeRoleNames the caller's held role names after active-role narrowing
+ * @param policies the target's matched policies in deterministic order
+ * @return the first matching policy, or empty
+ */
+ public static Optional<PolicyEntity> match(
+ Privilege.Name privilege, Set<String> activeRoleNames, List<PolicyEntity> policies) {
+ Objects.requireNonNull(privilege, "privilege must not be null");
+ Objects.requireNonNull(activeRoleNames, "activeRoleNames must not be null");
+ Objects.requireNonNull(policies, "policies must not be null");
+ if (activeRoleNames.isEmpty()
+ || !AccessControlContent.PERMITTED_PRIVILEGES.contains(privilege)) {
+ return Optional.empty();
+ }
+ for (PolicyEntity policy : policies) {
+ if (!policy.enabled() || policy.policyType() != Policy.BuiltInType.ACCESS_CONTROL) {
+ continue;
+ }
+ AccessControlContent content = (AccessControlContent) policy.content();
+ if (content.privileges().contains(privilege)
+ && !Collections.disjoint(content.applicableRoles(), activeRoleNames)) {
+ return Optional.of(policy);
+ }
+ }
+ return Optional.empty();
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java b/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java
index 73b22b013a..5cfaaff587 100644
--- a/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java
+++ b/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -35,6 +36,7 @@ import org.apache.gravitino.MetadataObject;
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.json.PolicyAssociationSelectorSerde;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.TagEntity;
@@ -95,17 +97,7 @@ public class ObjectPolicyResolver {
*/
public Match[] resolveMatches(String metalake, MetadataObject metadataObject) {
ResolvedTag[] effectiveTags = effectiveTagResolver.resolveWithSources(metalake, metadataObject);
- if (effectiveTags.length == 0) {
- return new Match[0];
- }
-
- List<NameIdentifier> tagIdentifiers =
- Arrays.stream(effectiveTags)
- .map(resolvedTag -> resolvedTag.tag().name())
- .distinct()
- .map(tagName -> NameIdentifierUtil.ofTag(metalake, tagName))
- .collect(Collectors.toList());
- return selectMatches(effectiveTags, loadRelations(tagIdentifiers, metadataObject));
+ return resolveMatches(metalake, metadataObject, effectiveTags);
}
/**
@@ -164,6 +156,49 @@ public class ObjectPolicyResolver {
return result;
}
+ /**
+ * Resolves the enabled access policies matched by a canonical target's effective tags.
+ *
+ * @param metalake the containing metalake
+ * @param target the original object whose access is being checked
+ * @param context the context shared by checks and list workers of this request
+ * @return immutable matched access policies in policy ID order
+ * @throws RuntimeException if resolution fails
+ */
+ public List<PolicyEntity> resolve(
+ String metalake, MetadataObject target, AuthorizationRequestContext context) {
+ Objects.requireNonNull(metalake, "metalake must not be null");
+ Objects.requireNonNull(target, "target must not be null");
+ Objects.requireNonNull(context, "context must not be null");
+ return context.computeTagPoliciesIfAbsent(
+ metalake,
+ target,
+ () -> {
+ ResolvedTag[] effectiveTags =
+ effectiveTagResolver.resolveWithSources(metalake, target, context);
+ return Arrays.stream(resolveMatches(metalake, target, effectiveTags))
+ .map(Match::policy)
+ .filter(policy -> policy.policyType() == Policy.BuiltInType.ACCESS_CONTROL)
+ .sorted(Comparator.comparingLong(PolicyEntity::id))
+ .collect(Collectors.toList());
+ });
+ }
+
+ private Match[] resolveMatches(
+ String metalake, MetadataObject metadataObject, ResolvedTag[] effectiveTags) {
+ if (effectiveTags.length == 0) {
+ return new Match[0];
+ }
+
+ List<NameIdentifier> tagIdentifiers =
+ Arrays.stream(effectiveTags)
+ .map(resolvedTag -> resolvedTag.tag().name())
+ .distinct()
+ .map(tagName -> NameIdentifierUtil.ofTag(metalake, tagName))
+ .collect(Collectors.toList());
+ return selectMatches(effectiveTags, loadRelations(tagIdentifiers, metadataObject));
+ }
+
private List<RelationalEntity<?>> loadRelations(
List<NameIdentifier> tagIdentifiers, Object request) {
@@ -189,18 +224,18 @@ public class ObjectPolicyResolver {
private static Match[] selectMatches(
ResolvedTag[] effectiveTags, List<RelationalEntity<?>> relations) {
- Map<String, ResolvedTag> tagsByName =
+ Map<NameIdentifier, ResolvedTag> tagsByIdentifier =
Arrays.stream(effectiveTags)
.collect(
Collectors.toMap(
- resolvedTag -> resolvedTag.tag().name(),
+ resolvedTag -> resolvedTag.tag().nameIdentifier(),
resolvedTag -> resolvedTag,
(left, right) -> left,
LinkedHashMap::new));
Map<Long, MatchState> matchStates = new LinkedHashMap<>();
for (RelationalEntity<?> relation : relations) {
- ResolvedTag resolvedTag = tagsByName.get(relation.source().name());
+ ResolvedTag resolvedTag = tagsByIdentifier.get(relation.source());
if (resolvedTag == null) {
continue;
}
@@ -225,13 +260,20 @@ public class ObjectPolicyResolver {
.toArray(Match[]::new);
}
+ /**
+ * Tests whether a selector accepts a tag assignment.
+ *
+ * @param selector the policy-to-tag association selector
+ * @param assignment the effective tag assignment
+ * @return whether the selector matches
+ * @throws IllegalArgumentException if the selector type is unsupported
+ */
private static boolean matches(PolicyAssociationSelector selector, TagAssignment assignment) {
if (selector instanceof AllValuesSelector) {
return true;
}
if (selector instanceof TagValueSelector) {
- String expectedValue = ((TagValueSelector) selector).value();
- return Arrays.asList(assignment.values()).contains(expectedValue);
+ return Arrays.asList(assignment.values()).contains(((TagValueSelector) selector).value());
}
throw new IllegalArgumentException(
"Unsupported policy association selector type: " + selector.type());
diff --git a/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java b/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java
index cc8e02dc73..9f47e28136 100644
--- a/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java
+++ b/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java
@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.function.Function;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
@@ -36,6 +37,7 @@ import org.apache.gravitino.MetadataObject;
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.catalog.CapabilityHelpers;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.exceptions.NoSuchEntityException;
@@ -93,38 +95,8 @@ public class EffectiveTagResolver {
*/
public ResolvedTag[] resolveWithSources(String metalake, MetadataObject metadataObject) {
MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
- List<MetadataObject> resolutionOrder = new ArrayList<>();
- resolutionOrder.add(metadataObject);
- resolutionOrder.addAll(MetadataObjectUtil.getParentMetadataObjects(metadataObject));
-
- Map<String, ResolvedTag> effectiveTags = new LinkedHashMap<>();
- for (int index = 0; index < resolutionOrder.size(); index++) {
- MetadataObject object = resolutionOrder.get(index);
- boolean inherited = index > 0;
- NameIdentifier identifier =
- MetadataObjectUtil.toEntityIdent(metalake, normalizeForLookup(metalake, object));
- Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);
- try {
- List<TagEntity> tags =
- entityStore
- .relationOperations()
- .listEntitiesByRelation(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- identifier,
- entityType);
- for (TagEntity tag : tags) {
- effectiveTags.putIfAbsent(
- tag.name(), new ResolvedTag(tag.copyWithInherited(inherited), object));
- }
- } catch (NoSuchEntityException e) {
- throw new NoSuchMetadataObjectException(
- e, "Failed to resolve effective tags for metadata object %s due to not found", object);
- } catch (IOException e) {
- LOG.error("Failed to resolve effective tags for metadata object {}", object, e);
- throw new RuntimeException(e);
- }
- }
- return effectiveTags.values().toArray(new ResolvedTag[0]);
+ return resolveWithSources(
+ metadataObject, object -> loadTags(metalake, normalizeForLookup(metalake, object), false));
}
/**
@@ -289,6 +261,64 @@ public class EffectiveTagResolver {
return result;
}
+ /**
+ * Resolves effective tags for an already normalized authorization target. Missing objects have no
+ * direct assignments and can still inherit tags from their ancestors.
+ *
+ * @param metalake the containing metalake
+ * @param target the canonical target
+ * @param context the request cache shared by privilege checks
+ * @return the effective assignments and their sources
+ */
+ public ResolvedTag[] resolveWithSources(
+ String metalake, MetadataObject target, AuthorizationRequestContext context) {
+ return resolveWithSources(
+ target,
+ object ->
+ context.computeDirectTagsIfAbsent(
+ metalake, object, () -> loadTags(metalake, object, true)));
+ }
+
+ private static ResolvedTag[] resolveWithSources(
+ MetadataObject metadataObject, Function<MetadataObject, List<TagEntity>> reader) {
+ List<MetadataObject> resolutionOrder = new ArrayList<>();
+ resolutionOrder.add(metadataObject);
+ resolutionOrder.addAll(MetadataObjectUtil.getParentMetadataObjects(metadataObject));
+
+ Map<String, ResolvedTag> effectiveTags = new LinkedHashMap<>();
+ for (int index = 0; index < resolutionOrder.size(); index++) {
+ MetadataObject object = resolutionOrder.get(index);
+ boolean inherited = index > 0;
+ reader
+ .apply(object)
+ .forEach(
+ tag ->
+ effectiveTags.putIfAbsent(
+ tag.name(), new ResolvedTag(tag.copyWithInherited(inherited), object)));
+ }
+ return effectiveTags.values().toArray(new ResolvedTag[0]);
+ }
+
+ private List<TagEntity> loadTags(String metalake, MetadataObject object, boolean allowMissing) {
+ NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);
+ Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);
+ try {
+ return entityStore
+ .relationOperations()
+ .listEntitiesByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL, identifier, entityType);
+ } catch (NoSuchEntityException e) {
+ if (allowMissing) {
+ return Collections.emptyList();
+ }
+ throw new NoSuchMetadataObjectException(
+ e, "Failed to resolve effective tags for metadata object %s due to not found", object);
+ } catch (IOException e) {
+ LOG.error("Failed to resolve effective tags for metadata object {}", object, e);
+ throw new RuntimeException(e);
+ }
+ }
+
private MetadataObject normalizeForLookup(String metalake, MetadataObject object) {
switch (object.type()) {
case SCHEMA:
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TagPolicyTestUtils.java b/core/src/test/java/org/apache/gravitino/authorization/TagPolicyTestUtils.java
new file mode 100644
index 0000000000..a4a80c2f29
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/authorization/TagPolicyTestUtils.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.authorization;
+
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContents;
+import org.apache.gravitino.utils.NamespaceUtil;
+
+/** Shared tag-policy entities for authorization tests. */
+final class TagPolicyTestUtils {
+ static final String METALAKE = "metalake";
+
+ private TagPolicyTestUtils() {}
+
+ static PolicyEntity policy(
+ long id, boolean enabled, List<Privilege.Name> privileges, List<String> roles) {
+ return PolicyEntity.builder()
+ .withId(id)
+ .withName("policy_" + id)
+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE))
+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+ .withEnabled(enabled)
+ .withContent(PolicyContents.accessControl(privileges, roles))
+ .withAuditInfo(audit())
+ .build();
+ }
+
+ static AuditInfo audit() {
+ return AuditInfo.builder().withCreator("tester").withCreateTime(Instant.EPOCH).build();
+ }
+
+ static PolicyEntity customPolicy() {
+ return PolicyEntity.builder()
+ .withId(99L)
+ .withName("custom")
+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE))
+ .withPolicyType(Policy.BuiltInType.CUSTOM)
+ .withEnabled(true)
+ .withContent(
+ PolicyContents.custom(
+ Collections.singletonMap("rule", "value"),
+ Collections.singleton(MetadataObject.Type.TABLE),
+ Collections.emptyMap()))
+ .withAuditInfo(audit())
+ .build();
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationRequestContext.java b/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationRequestContext.java
index 7c30896fc8..29c51c2193 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationRequestContext.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAuthorizationRequestContext.java
@@ -52,6 +52,80 @@ import org.junit.jupiter.api.Test;
public class TestAuthorizationRequestContext {
+ /** Tests policy-existence lookup reuse across concurrent workers of one request. */
+ @Test
+ public void testEnabledAccessPolicyCheckRunsOncePerMetalake() throws Exception {
+ AuthorizationRequestContext context = new AuthorizationRequestContext();
+ AtomicInteger reads = new AtomicInteger();
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch secondStarted = new CountDownLatch(1);
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Callable<Boolean> lookup =
+ () ->
+ context.hasEnabledAccessPolicies(
+ "metalake",
+ () -> {
+ reads.incrementAndGet();
+ entered.countDown();
+ try {
+ assertTrue(release.await(5, TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ return false;
+ });
+ Future<Boolean> first = workers.submit(lookup);
+ assertTrue(entered.await(5, TimeUnit.SECONDS));
+ Future<Boolean> second =
+ workers.submit(
+ () -> {
+ secondStarted.countDown();
+ return lookup.call();
+ });
+ assertTrue(secondStarted.await(5, TimeUnit.SECONDS));
+ // A concurrent check must wait for the in-flight lookup instead of running another query.
+ assertThrows(TimeoutException.class, () -> second.get(200, TimeUnit.MILLISECONDS));
+ release.countDown();
+ assertFalse(first.get(5, TimeUnit.SECONDS));
+ assertFalse(second.get(5, TimeUnit.SECONDS));
+ assertFalse(context.hasEnabledAccessPolicies("metalake", () -> true));
+ assertEquals(1, reads.get());
+ assertTrue(context.hasEnabledAccessPolicies("another", () -> true));
+ assertTrue(
+ new AuthorizationRequestContext().hasEnabledAccessPolicies("metalake", () -> true));
+ } finally {
+ release.countDown();
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ /** Tests that lookup failures are retained only for the current request. */
+ @Test
+ public void testEnabledAccessPolicyCheckRetainsFailure() {
+ AuthorizationRequestContext context = new AuthorizationRequestContext();
+ RuntimeException failure = new IllegalStateException("policy listing failed");
+ assertSame(
+ failure,
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ context.hasEnabledAccessPolicies(
+ "metalake",
+ () -> {
+ throw failure;
+ })));
+ assertSame(
+ failure,
+ assertThrows(
+ IllegalStateException.class,
+ () -> context.hasEnabledAccessPolicies("metalake", () -> true)));
+ assertTrue(new AuthorizationRequestContext().hasEnabledAccessPolicies("metalake", () -> true));
+ }
+
@Test
public void testLoadRoleRunsOnceEvenWhenInvokedConcurrently() throws Exception {
AuthorizationRequestContext context = new AuthorizationRequestContext();
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestTagPolicyMatcher.java b/core/src/test/java/org/apache/gravitino/authorization/TestTagPolicyMatcher.java
new file mode 100644
index 0000000000..79ea9cd178
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestTagPolicyMatcher.java
@@ -0,0 +1,117 @@
+/*
+ * 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.authorization;
+
+import static org.apache.gravitino.authorization.TagPolicyTestUtils.customPolicy;
+import static org.apache.gravitino.authorization.TagPolicyTestUtils.policy;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.apache.gravitino.auth.ActiveRoles;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests privilege and active-role matching without storage. */
+class TestTagPolicyMatcher {
+ @Test
+ void testAnyActiveRoleCanMatchEveryListedPrivilege() {
+ PolicyEntity matchedPolicy = accessPolicy(true);
+ for (Privilege.Name privilege :
+ Arrays.asList(Privilege.Name.SELECT_TABLE, Privilege.Name.MODIFY_TABLE)) {
+ for (String role : Arrays.asList("analyst", "engineer")) {
+ PolicyEntity match =
+ TagPolicyMatcher.match(privilege, Set.of("unrelated", role), List.of(matchedPolicy))
+ .orElseThrow();
+ Assertions.assertSame(matchedPolicy, match);
+ Assertions.assertEquals(10L, match.id());
+ }
+ }
+ }
+
+ @Test
+ void testInactiveAndNoActiveRolesDoNotMatch() {
+ List<PolicyEntity> policies = List.of(accessPolicy(true));
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(Privilege.Name.SELECT_TABLE, Set.of("unrelated"), policies)
+ .isPresent());
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(
+ Privilege.Name.SELECT_TABLE, ActiveRoles.none().roleNames(), policies)
+ .isPresent());
+ }
+
+ @Test
+ void testUnlistedAndNonConferrablePrivilegesDoNotMatch() {
+ List<PolicyEntity> policies = List.of(accessPolicy(true));
+ for (Privilege.Name privilege :
+ Arrays.asList(
+ Privilege.Name.READ_FILESET, Privilege.Name.USE_SCHEMA, Privilege.Name.MANAGE_GRANTS)) {
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(privilege, Set.of("analyst"), policies).isPresent());
+ }
+ }
+
+ @Test
+ void testDisabledPoliciesAndAbsentBindingsDoNotMatch() {
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(
+ Privilege.Name.SELECT_TABLE, Set.of("analyst"), List.of(accessPolicy(false)))
+ .isPresent());
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(
+ Privilege.Name.SELECT_TABLE, Set.of("analyst"), Collections.emptyList())
+ .isPresent());
+ }
+
+ @Test
+ void testNonmatchingPolicyDoesNotHideLaterMatch() {
+ PolicyEntity nonmatch =
+ policy(9L, true, List.of(Privilege.Name.SELECT_TABLE), List.of("unrelated"));
+ PolicyEntity match = accessPolicy(true);
+ List<PolicyEntity> policies = List.of(nonmatch, match);
+ Set<String> roles = Set.of("analyst");
+ Assertions.assertSame(
+ match, TagPolicyMatcher.match(Privilege.Name.SELECT_TABLE, roles, policies).orElseThrow());
+ Assertions.assertSame(
+ match, TagPolicyMatcher.match(Privilege.Name.SELECT_TABLE, roles, policies).orElseThrow());
+ Assertions.assertEquals(List.of(nonmatch, match), policies);
+ Assertions.assertEquals(Set.of("analyst"), roles);
+ }
+
+ @Test
+ void testGovernancePolicyCannotConferAccess() {
+ PolicyEntity matchedPolicy = customPolicy();
+ Assertions.assertFalse(
+ TagPolicyMatcher.match(
+ Privilege.Name.SELECT_TABLE, Set.of("analyst"), List.of(matchedPolicy))
+ .isPresent());
+ }
+
+ private static PolicyEntity accessPolicy(boolean enabled) {
+ return policy(
+ 10L,
+ enabled,
+ List.of(Privilege.Name.SELECT_TABLE, Privilege.Name.MODIFY_TABLE),
+ List.of("analyst", "engineer"));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java b/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java
index 2520d7e40d..676529b29f 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestObjectPolicyResolver.java
@@ -40,6 +40,8 @@ import org.apache.gravitino.MetadataObjects;
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.Privilege;
import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.PolicyEntity;
@@ -109,6 +111,39 @@ public class TestObjectPolicyResolver {
Assertions.assertEquals(List.of(OBJECT, CATALOG), matches[0].sources());
}
+ @Test
+ void testRequestResolutionCachesOnlyMatchedAccessPolicies() throws Exception {
+ AuthorizationRequestContext context = new AuthorizationRequestContext();
+ TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance"));
+ PolicyEntity access =
+ PolicyEntity.builder()
+ .withId(11L)
+ .withName("read_finance")
+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE))
+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+ .withEnabled(true)
+ .withContent(
+ PolicyContents.accessControl(
+ List.of(Privilege.Name.SELECT_TABLE), List.of("analyst")))
+ .withAuditInfo(audit())
+ .build();
+ when(effectiveTagResolver.resolveWithSources(METALAKE, OBJECT, context))
+ .thenReturn(new ResolvedTag[] {new ResolvedTag(domain, OBJECT)});
+ when(relationOperations.batchListEntitiesByRelation(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ List.of(domain.nameIdentifier()),
+ Entity.EntityType.TAG))
+ .thenReturn(
+ List.of(
+ relation(domain, policy(10L, "custom", true), AllValuesSelector.get()),
+ relation(domain, access, TagValueSelector.of("finance"))));
+
+ List<PolicyEntity> policies = resolver.resolve(METALAKE, OBJECT, context);
+ Assertions.assertEquals(List.of(access), policies);
+ Assertions.assertSame(policies, resolver.resolve(METALAKE, OBJECT, context));
+ verify(effectiveTagResolver).resolveWithSources(METALAKE, OBJECT, context);
+ }
+
@Test
public void testResolveMissingSelectorAsAllValues() throws Exception {
TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("finance")).copyWithInherited(true);
@@ -135,6 +170,26 @@ public class TestObjectPolicyResolver {
List.of(CATALOG), resolver.resolveMatches(METALAKE, OBJECT)[0].sources());
}
+ @Test
+ public void testSameTagNameFromAnotherMetalakeDoesNotMatch() throws Exception {
+ TagEntity domain = tag(1L, "domain", TagAssignment.noValue());
+ when(effectiveTagResolver.resolveWithSources(METALAKE, OBJECT))
+ .thenReturn(new ResolvedTag[] {new ResolvedTag(domain, OBJECT)});
+ when(relationOperations.batchListEntitiesByRelation(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ List.of(domain.nameIdentifier()),
+ Entity.EntityType.TAG))
+ .thenReturn(
+ List.of(
+ new RelationalEntity<>(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ NameIdentifierUtil.ofTag("other", "domain"),
+ Entity.EntityType.TAG,
+ policy(10L, "policy", true),
+ null)));
+ Assertions.assertEquals(0, resolver.resolve(METALAKE, OBJECT).length);
+ }
+
@Test
public void testDropNonMatchingSelector() throws Exception {
TagEntity domain = tag(1L, "domain", TagAssignment.ofValues("engineering"));
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java b/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java
index 39b1b8c59d..57d1a39cef 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestEffectiveTagResolver.java
@@ -46,6 +46,7 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
@@ -176,6 +177,32 @@ public class TestEffectiveTagResolver {
Assertions.assertFalse(effectiveTags[0].tag().inherited().orElseThrow());
}
+ @Test
+ void testRequestResolutionSharesAncestorTagsForMissingTarget() throws Exception {
+ AuthorizationRequestContext context = new AuthorizationRequestContext();
+ NameIdentifier schema = MetadataObjectUtil.toEntityIdent(METALAKE, SCHEMA);
+ when(relationOperations.listEntitiesByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ MetadataObjectUtil.toEntityIdent(METALAKE, TABLE),
+ Entity.EntityType.TABLE))
+ .thenThrow(new NoSuchEntityException("missing table"));
+ when(relationOperations.listEntitiesByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ schema,
+ Entity.EntityType.SCHEMA))
+ .thenReturn(List.of(tag(1L, "tier", TagAssignment.ofValues("gold"))));
+
+ Assertions.assertEquals(
+ SCHEMA, resolver.resolveWithSources(METALAKE, TABLE, context)[0].source());
+ Assertions.assertEquals(
+ SCHEMA, resolver.resolveWithSources(METALAKE, SCHEMA, context)[0].source());
+ verify(relationOperations)
+ .listEntitiesByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ schema,
+ Entity.EntityType.SCHEMA);
+ }
+
@Test
void testMissingObjectIsTranslated() throws Exception {
NoSuchEntityException exception = new NoSuchEntityException("missing");