Skip to content

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

[#15153] feat(core): Refuse deleting a role that an access policy names (#15155)

Bharath Krishnaf676fe210e30
diff --git a/clients/cli/src/main/java/org/apache/gravitino/cli/commands/DeleteRole.java b/clients/cli/src/main/java/org/apache/gravitino/cli/commands/DeleteRole.java
index 5a4a3b6d82..6bf50a6926 100644
--- a/clients/cli/src/main/java/org/apache/gravitino/cli/commands/DeleteRole.java
+++ b/clients/cli/src/main/java/org/apache/gravitino/cli/commands/DeleteRole.java
@@ -26,6 +26,7 @@ import org.apache.gravitino.cli.AreYouSure;
import org.apache.gravitino.cli.CommandContext;
import org.apache.gravitino.cli.ErrorMessages;
import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
@@ -62,11 +63,17 @@ public class DeleteRole extends Command {
}
List<String> failedRoles = Lists.newArrayList();
List<String> successRoles = Lists.newArrayList();
+ List<String> inUseErrors = Lists.newArrayList();
try {
GravitinoClient client = buildClient(metalake);
for (String role : roles) {
- (client.deleteRole(role) ? successRoles : failedRoles).add(role);
+ try {
+ (client.deleteRole(role) ? successRoles : failedRoles).add(role);
+ } catch (InUseException err) {
+ // An access control policy still names this role; try the rest and report it after.
+ inUseErrors.add(err.getMessage());
+ }
}
} catch (NoSuchMetalakeException err) {
exitWithError(ErrorMessages.UNKNOWN_METALAKE);
@@ -76,6 +83,15 @@ public class DeleteRole extends Command {
exitWithError(exp.getMessage());
}
+ if (!successRoles.isEmpty() || !failedRoles.isEmpty()) {
+ printDeletions(successRoles, failedRoles);
+ }
+ if (!inUseErrors.isEmpty()) {
+ exitWithError(String.join(System.lineSeparator(), inUseErrors));
+ }
+ }
+
+ private void printDeletions(List<String> successRoles, List<String> failedRoles) {
if (failedRoles.isEmpty()) {
printInformation(COMMA_JOINER.join(successRoles) + " deleted.");
} else {
diff --git a/clients/cli/src/test/java/org/apache/gravitino/cli/commands/TestDeleteRole.java b/clients/cli/src/test/java/org/apache/gravitino/cli/commands/TestDeleteRole.java
new file mode 100644
index 0000000000..d8aa9dc0c9
--- /dev/null
+++ b/clients/cli/src/test/java/org/apache/gravitino/cli/commands/TestDeleteRole.java
@@ -0,0 +1,88 @@
+/*
+ * 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.cli.commands;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import org.apache.commons.cli.CommandLine;
+import org.apache.gravitino.cli.CommandContext;
+import org.apache.gravitino.cli.GravitinoOptions;
+import org.apache.gravitino.cli.Main;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.exceptions.InUseException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestDeleteRole {
+
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+ private final PrintStream originalErr = System.err;
+
+ @BeforeEach
+ void setup() {
+ System.setOut(new PrintStream(outContent));
+ System.setErr(new PrintStream(errContent));
+ }
+
+ @AfterEach
+ void restore() {
+ System.setOut(originalOut);
+ System.setErr(originalErr);
+ Main.useExit = true;
+ }
+
+ @Test
+ void referencedRoleDoesNotStopTheRemainingDeletions() {
+ Main.useExit = false;
+ CommandLine mockCmdLine = mock(CommandLine.class);
+ when(mockCmdLine.hasOption(GravitinoOptions.FORCE)).thenReturn(true);
+ CommandContext context = new CommandContext(mockCmdLine);
+
+ DeleteRole command =
+ spy(new DeleteRole(context, "metalake1", new String[] {"referenced", "unused"}));
+ GravitinoClient mockClient = mock(GravitinoClient.class);
+ doReturn(mockClient).when(command).buildClient("metalake1");
+ doThrow(new InUseException("Role referenced is referenced by access control policies"))
+ .when(mockClient)
+ .deleteRole("referenced");
+ doReturn(true).when(mockClient).deleteRole("unused");
+
+ RuntimeException ex = assertThrows(RuntimeException.class, command::handle);
+
+ assertTrue(ex.getMessage().contains("Exit with code -1"));
+ verify(mockClient).deleteRole("unused");
+ assertTrue(outContent.toString(UTF_8).contains("unused deleted."));
+ assertTrue(
+ errContent.toString(UTF_8).contains("referenced is referenced by access control policies"));
+ }
+}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
index f136686b36..e4fe43b475 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
@@ -984,6 +984,9 @@ public class ErrorHandlers {
case ErrorConstants.NOT_IN_USE_CODE:
throw new MetalakeNotInUseException(errorMessage);
+ case ErrorConstants.IN_USE_CODE:
+ throw new InUseException(errorMessage);
+
case ErrorConstants.INTERNAL_ERROR_CODE:
throw new RuntimeException(errorMessage);
@@ -1206,6 +1209,10 @@ public class ErrorHandlers {
switch (errorResponse.getCode()) {
case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:
+ // An access control policy naming a role that does not exist.
+ if (errorResponse.getType().equals(IllegalRoleException.class.getSimpleName())) {
+ throw new IllegalRoleException(errorMessage);
+ }
throw new IllegalArgumentException(errorMessage);
case ErrorConstants.NOT_FOUND_CODE:
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestErrorHandlers.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestErrorHandlers.java
index 9723345fa5..68c9651eee 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestErrorHandlers.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestErrorHandlers.java
@@ -25,6 +25,7 @@ import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.exceptions.IllegalRoleException;
import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.exceptions.ServiceUnavailableException;
import org.junit.jupiter.api.Assertions;
@@ -33,6 +34,26 @@ import org.junit.jupiter.api.Test;
/** Tests REST error handling for cross-cutting error codes. */
public class TestErrorHandlers {
+ @Test
+ public void testPolicyErrorHandlerKeepsIllegalRoleException() {
+ Consumer<ErrorResponse> handler = ErrorHandlers.policyErrorHandler();
+
+ IllegalRoleException missingRole =
+ Assertions.assertThrows(
+ IllegalRoleException.class,
+ () ->
+ handler.accept(
+ ErrorResponse.illegalArguments(
+ IllegalRoleException.class.getSimpleName(), "no role analyst", null)));
+ Assertions.assertTrue(missingRole.getMessage().contains("no role analyst"));
+
+ IllegalArgumentException other =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> handler.accept(ErrorResponse.illegalArguments("bad content")));
+ Assertions.assertEquals(IllegalArgumentException.class, other.getClass());
+ }
+
@Test
@SuppressWarnings("unchecked")
public void testServiceUnavailableAcrossHandlers() throws ReflectiveOperationException {
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRole.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRole.java
index 035d330afc..5e80d369a4 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRole.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRole.java
@@ -42,6 +42,7 @@ import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.responses.MetalakeResponse;
import org.apache.gravitino.dto.responses.NameListResponse;
import org.apache.gravitino.dto.responses.RoleResponse;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
import org.apache.gravitino.exceptions.RoleAlreadyExistsException;
@@ -210,6 +211,13 @@ public class TestRole extends TestBase {
ErrorResponse errResp = ErrorResponse.internalError("internal error");
buildMockResource(Method.DELETE, rolePath, null, errResp, SC_SERVER_ERROR);
Assertions.assertThrows(RuntimeException.class, () -> gravitinoClient.deleteRole(roleName));
+
+ // test InUseException, for a role that an access control policy names
+ ErrorResponse inUseResp =
+ ErrorResponse.inUse(
+ InUseException.class.getSimpleName(), "role is referenced by policies", null);
+ buildMockResource(Method.DELETE, rolePath, null, inUseResp, SC_CONFLICT);
+ Assertions.assertThrows(InUseException.class, () -> gravitinoClient.deleteRole(roleName));
}
@Test
diff --git a/clients/client-python/gravitino/exceptions/handlers/policy_error_handler.py b/clients/client-python/gravitino/exceptions/handlers/policy_error_handler.py
index e799cedfe3..f1089c61da 100644
--- a/clients/client-python/gravitino/exceptions/handlers/policy_error_handler.py
+++ b/clients/client-python/gravitino/exceptions/handlers/policy_error_handler.py
@@ -17,7 +17,7 @@
from gravitino.constants.error import ErrorConstants
from gravitino.exceptions.base import (
- IllegalArgumentException,
+ IllegalRoleException,
MetalakeNotInUseException,
NoSuchMetalakeException,
NoSuchPolicyException,
@@ -31,7 +31,11 @@ class PolicyErrorHandler(CodeMappingErrorHandler):
"""Error handler specific to Policy operations."""
_code_exception_map = {
- ErrorConstants.ILLEGAL_ARGUMENTS_CODE: IllegalArgumentException,
+ # A policy naming a role that does not exist. Other types fall back to the
+ # generic IllegalArgumentException.
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE: {
+ IllegalRoleException.__name__: IllegalRoleException,
+ },
ErrorConstants.NOT_FOUND_CODE: {
NoSuchMetalakeException.__name__: NoSuchMetalakeException,
NoSuchPolicyException.__name__: NoSuchPolicyException,
diff --git a/clients/client-python/gravitino/exceptions/handlers/role_error_handler.py b/clients/client-python/gravitino/exceptions/handlers/role_error_handler.py
index 56282a9096..92c18eeec7 100644
--- a/clients/client-python/gravitino/exceptions/handlers/role_error_handler.py
+++ b/clients/client-python/gravitino/exceptions/handlers/role_error_handler.py
@@ -20,6 +20,7 @@ from gravitino.exceptions.base import (
ForbiddenException,
IllegalMetadataObjectException,
IllegalPrivilegeException,
+ InUseException,
MetalakeNotInUseException,
NoSuchMetadataObjectException,
NoSuchMetalakeException,
@@ -47,6 +48,7 @@ class RoleErrorHandler(CodeMappingErrorHandler):
ErrorConstants.UNSUPPORTED_OPERATION_CODE: UnsupportedOperationException,
ErrorConstants.FORBIDDEN_CODE: ForbiddenException,
ErrorConstants.NOT_IN_USE_CODE: MetalakeNotInUseException,
+ ErrorConstants.IN_USE_CODE: InUseException,
ErrorConstants.INTERNAL_ERROR_CODE: RuntimeError,
}
diff --git a/clients/client-python/tests/unittests/test_error_handler.py b/clients/client-python/tests/unittests/test_error_handler.py
index f2bf283627..fb16e65572 100644
--- a/clients/client-python/tests/unittests/test_error_handler.py
+++ b/clients/client-python/tests/unittests/test_error_handler.py
@@ -33,6 +33,7 @@ from gravitino.exceptions.base import (
IllegalPrivilegeException,
IllegalRoleException,
IllegalStatisticNameException,
+ InUseException,
InternalError,
MetalakeAlreadyExistsException,
MetalakeNotInUseException,
@@ -87,6 +88,7 @@ from gravitino.exceptions.handlers.semantic_model_error_handler import (
from gravitino.exceptions.handlers.permission_error_handler import (
PERMISSION_ERROR_HANDLER,
)
+from gravitino.exceptions.handlers.policy_error_handler import POLICY_ERROR_HANDLER
from gravitino.exceptions.handlers.role_error_handler import ROLE_ERROR_HANDLER
from gravitino.exceptions.handlers.schema_error_handler import SCHEMA_ERROR_HANDLER
from gravitino.exceptions.handlers.table_error_handler import TABLE_ERROR_HANDLER
@@ -842,6 +844,11 @@ class TestErrorHandler(unittest.TestCase):
)
)
+ with self.assertRaises(InUseException):
+ ROLE_ERROR_HANDLER.handle(
+ ErrorResponse.generate_error_response(InUseException, "mock error")
+ )
+
with self.assertRaises(RuntimeError):
ROLE_ERROR_HANDLER.handle(
ErrorResponse.generate_error_response(InternalError, "mock error")
@@ -941,6 +948,22 @@ class TestErrorHandler(unittest.TestCase):
ErrorResponse.generate_error_response(NotFoundException, "mock error")
)
+ def test_policy_error_handler_keeps_illegal_role(self):
+ with self.assertRaises(IllegalRoleException):
+ POLICY_ERROR_HANDLER.handle(
+ ErrorResponse.generate_error_response(
+ IllegalRoleException, "mock error"
+ )
+ )
+
+ with self.assertRaises(IllegalArgumentException) as context:
+ POLICY_ERROR_HANDLER.handle(
+ ErrorResponse.generate_error_response(
+ IllegalArgumentException, "mock error"
+ )
+ )
+ self.assertIs(type(context.exception), IllegalArgumentException)
+
def test_semantic_model_error_handler(self):
with self.assertRaises(IllegalSemanticModelException):
SEMANTIC_MODEL_ERROR_HANDLER.handle(
diff --git a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
index 4fd09df4e7..844062b21d 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/AuthorizationUtils.java
@@ -70,6 +70,11 @@ public class AuthorizationUtils {
static final String GROUP_DOES_NOT_EXIST_MSG = "Group %s does not exist in the metalake %s";
static final String ROLE_DOES_NOT_EXIST_MSG = "Role %s does not exist in the metalake %s";
+ /** Message for deleting a role that an access control policy names; takes role and metalake. */
+ public static final String ROLE_IN_USE_MSG =
+ "Role %s in metalake %s is referenced by access control policies; remove it from those"
+ + " policies before deleting it";
+
/**
* Bidirectional map of deprecated privilege names to their new equivalents. This map is used for
* backward compatibility when handling legacy privilege names.
diff --git a/core/src/main/java/org/apache/gravitino/authorization/RoleManager.java b/core/src/main/java/org/apache/gravitino/authorization/RoleManager.java
index 94c35c3e8a..07dea1d334 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/RoleManager.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/RoleManager.java
@@ -111,20 +111,16 @@ class RoleManager {
boolean deleteRole(String metalake, String role) {
try {
NameIdentifier ident = AuthorizationUtils.ofRole(metalake, role);
-
- try {
- RoleEntity roleEntity = store.get(ident, Entity.EntityType.ROLE, RoleEntity.class);
- AuthorizationUtils.callAuthorizationPluginForSecurableObjects(
- metalake,
- roleEntity.securableObjects(),
- (authorizationPlugin, catalogName) ->
- authorizationPlugin.onRoleDeleted(
- AuthorizationUtils.filterSecurableObjects(roleEntity, metalake, catalogName)));
- } catch (NoSuchEntityException nse) {
- // ignore, because the role may have been deleted.
- }
-
- return store.delete(ident, Entity.EntityType.ROLE);
+ // The store refuses a role that an access control policy names, and holds the role locked
+ // until it commits, so the plugins run only for a deletion that goes ahead. A plugin failure
+ // rolls the deletion back, which leaves the role for a retry to reach the plugins again.
+ return store
+ .deleteAndGet(
+ ident,
+ Entity.EntityType.ROLE,
+ RoleEntity.class,
+ roleEntity -> notifyRoleDeleted(metalake, roleEntity))
+ .isPresent();
} catch (IOException ioe) {
LOG.error(
"Deleting role {} in the metalake {} failed due to storage issues", role, metalake, ioe);
@@ -173,6 +169,15 @@ class RoleManager {
}
}
+ private static void notifyRoleDeleted(String metalake, RoleEntity roleEntity) {
+ AuthorizationUtils.callAuthorizationPluginForSecurableObjects(
+ metalake,
+ roleEntity.securableObjects(),
+ (authorizationPlugin, catalogName) ->
+ authorizationPlugin.onRoleDeleted(
+ AuthorizationUtils.filterSecurableObjects(roleEntity, metalake, catalogName)));
+ }
+
private RoleEntity getRoleEntity(NameIdentifier identifier) {
try {
return store.get(identifier, Entity.EntityType.ROLE, RoleEntity.class);
diff --git a/core/src/main/java/org/apache/gravitino/bulk/BulkManager.java b/core/src/main/java/org/apache/gravitino/bulk/BulkManager.java
index 1fccbc55c4..cdcf598949 100644
--- a/core/src/main/java/org/apache/gravitino/bulk/BulkManager.java
+++ b/core/src/main/java/org/apache/gravitino/bulk/BulkManager.java
@@ -24,6 +24,7 @@ import org.apache.gravitino.dto.responses.BulkError;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.exceptions.AlreadyExistsException;
import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.exceptions.NotInUseException;
@@ -70,6 +71,8 @@ public class BulkManager {
return ErrorConstants.FORBIDDEN_CODE;
} else if (e instanceof NotInUseException) {
return ErrorConstants.NOT_IN_USE_CODE;
+ } else if (e instanceof InUseException) {
+ return ErrorConstants.IN_USE_CODE;
}
return ErrorConstants.INTERNAL_ERROR_CODE;
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index 39ce868b6a..b79db9dbdd 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -495,14 +495,22 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
Class<E> clazz,
Consumer<E> postDeleteAction)
throws IOException {
- if (entityType != Entity.EntityType.FILESET) {
- return RelationalBackend.super.deleteAndGet(ident, entityType, clazz, postDeleteAction);
+ switch (entityType) {
+ case FILESET:
+ return deleteWithCallback(
+ ident,
+ entityType,
+ () -> clazz.cast(FilesetMetaService.getInstance().deleteFilesetAndGet(ident)),
+ postDeleteAction);
+ case ROLE:
+ return deleteWithCallback(
+ ident,
+ entityType,
+ () -> clazz.cast(RoleMetaService.getInstance().deleteRoleAndGet(ident)),
+ postDeleteAction);
+ default:
+ return RelationalBackend.super.deleteAndGet(ident, entityType, clazz, postDeleteAction);
}
- return deleteWithCallback(
- ident,
- entityType,
- () -> clazz.cast(FilesetMetaService.getInstance().deleteFilesetAndGet(ident)),
- postDeleteAction);
}
@Override
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
index 31288efbec..a888f7e680 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metrics.Monitored;
@@ -142,6 +143,7 @@ public class PolicyMetaService {
SessionUtils.doMultipleWithCommit(
() -> lockMetalakeForPolicyCreate(metalakePO),
+ () -> lockNamedRoles(metalakePO.getMetalakeId(), policyEntity),
() -> insertPolicyWithoutCommit(policyEntity, policyPO, overwritten));
} catch (UncheckedIOException e) {
throw e.getCause();
@@ -182,6 +184,7 @@ public class PolicyMetaService {
PolicyPO newPolicyPO =
POConverters.updatePolicyPOWithVersion(oldPolicyPO, updatedPolicyEntity);
SessionUtils.doMultipleWithCommit(
+ () -> lockForUpdate(metalakeName, oldPolicyPO.getMetalakeId(), updatedPolicyEntity),
() -> beforeUpdate(updatedPolicyEntity),
() -> updatePolicyRootWithVersion(ident, oldPolicyPO, newPolicyPO),
() -> insertPolicyVersionIfAllocated(oldPolicyPO, newPolicyPO),
@@ -386,6 +389,37 @@ public class PolicyMetaService {
current -> Objects.equals(current.getMetalakeName(), observedMetalakePO.getMetalakeName()));
}
+ /**
+ * Takes the locks an update needs before it writes the policy row: the metalake row in share
+ * mode, then the roles the updated content names, the order role and metalake deletion use. An
+ * update that names no roles takes neither, so it doesn't wait on edits to other policies in the
+ * metalake; H2 takes the share lock exclusively.
+ */
+ private void lockForUpdate(String metalakeName, Long metalakeId, PolicyEntity policyEntity) {
+ if (POConverters.policyRoleNames(policyEntity).isEmpty()) {
+ return;
+ }
+ LiveEndpointService.lockLiveEndpoint(
+ NameIdentifier.of(metalakeName),
+ Entity.EntityType.METALAKE,
+ new NamespacedEntityId(metalakeId));
+ lockNamedRoles(metalakeId, policyEntity);
+ }
+
+ /**
+ * Requires the roles the policy content names to exist, and holds them until commit so none can
+ * be deleted while this write is in flight. Runs after the metalake lock and before the policy
+ * row is written; see {@link RoleMetaService#lockRolesNamedByPolicy}.
+ */
+ private void lockNamedRoles(Long metalakeId, PolicyEntity policyEntity) {
+ Set<String> roleNames = POConverters.policyRoleNames(policyEntity);
+ if (roleNames.isEmpty()) {
+ return;
+ }
+ RoleMetaService.getInstance()
+ .lockRolesNamedByPolicy(metalakeId, policyEntity.nameIdentifier(), roleNames);
+ }
+
/**
* Writes the policy row, its content snapshot, and the role references derived from that content.
*/
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java
index d6e7462e17..849d5723af 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/RoleMetaService.java
@@ -34,6 +34,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -44,6 +45,8 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.exceptions.IllegalRoleException;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
@@ -54,6 +57,7 @@ import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.GroupRoleRelMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;
import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.UserRoleRelMapper;
@@ -359,6 +363,64 @@ public class RoleMetaService {
}
}
+ /**
+ * Requires every role an access control policy names to exist, and holds those roles until the
+ * surrounding policy write commits.
+ *
+ * <p>A role cannot be deleted while a policy names it, so a policy cannot name a missing role
+ * either. Each name is resolved to its live role, whose row is then locked in share mode and read
+ * again. Role deletion locks the same row exclusively before it looks for references, so the two
+ * serialize. If the policy write locks first, the deletion waits and then sees the committed
+ * reference. If the deletion locks first, the row is gone once it commits and the policy write
+ * fails. Shared locks let policies naming the same role be written at the same time; H2 uses
+ * exclusive locks instead.
+ *
+ * <p>Call after locking the metalake and before writing the policy row. Policy writes, role
+ * deletion and metalake deletion then all lock in the order metalake, role, policy. Roles are
+ * locked in ascending ID order.
+ *
+ * @param metalakeId the ID of the policy's metalake
+ * @param policy the policy being written, used only in the error
+ * @param roleNames the role names the policy content names
+ * @throws IllegalRoleException if a named role does not exist in the metalake
+ * @throws IllegalStateException if called outside a transaction
+ */
+ void lockRolesNamedByPolicy(
+ Long metalakeId, NameIdentifier policy, Collection<String> roleNames) {
+ Preconditions.checkState(
+ SessionUtils.isInTransaction(), "Policy role locks require an active transaction");
+ // A name lookup earlier in the caller's transaction may still be in MyBatis's session cache.
+ SessionUtils.clearSessionCache();
+ Map<Long, RolePO> resolved = new TreeMap<>();
+ for (String roleName : roleNames) {
+ RolePO role =
+ SessionUtils.getWithoutCommit(
+ RoleMetaMapper.class,
+ mapper -> mapper.selectRoleMetaByMetalakeIdAndName(metalakeId, roleName));
+ // MySQL's collation ignores trailing spaces, so "analyst " finds the role "analyst". The
+ // policy keeps the name as written and matches roles by exact name, so require an exact one.
+ if (role == null || !roleName.equals(role.getRoleName())) {
+ throw missingPolicyRole(policy, roleName);
+ }
+ resolved.putIfAbsent(role.getRoleId(), role);
+ }
+
+ for (RolePO role : resolved.values()) {
+ RolePO locked =
+ SessionUtils.getWithoutCommit(
+ RoleMetaMapper.class, mapper -> mapper.selectRoleMetaByIdForShare(role.getRoleId()));
+ if (locked == null || !isSameRole(locked, role)) {
+ throw missingPolicyRole(policy, role.getRoleName());
+ }
+ }
+ }
+
+ private static IllegalRoleException missingPolicyRole(NameIdentifier policy, String roleName) {
+ return new IllegalRoleException(
+ "Policy %s names role %s, which does not exist in metalake %s",
+ policy.name(), roleName, policy.namespace().level(0));
+ }
+
private List<SecurableObjectPO> toSecurableObjectPOs(
Set<SecurableObject> deleteObjects, RoleEntity oldRoleEntity, String metalake) {
List<SecurableObjectPO> securableObjectPOs = Lists.newArrayList();
@@ -407,6 +469,31 @@ public class RoleMetaService {
return true;
}
+ /**
+ * Deletes a role and returns it, securable objects included, as it was before the deletion. Run
+ * inside a caller's transaction, the role stays locked until that transaction ends, so the caller
+ * can act on the deleted role before committing.
+ *
+ * @param identifier the role identifier
+ * @return the deleted role
+ * @throws InUseException if an access control policy names the role
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "deleteRoleAndGet")
+ public RoleEntity deleteRoleAndGet(NameIdentifier identifier) {
+ AuthorizationUtils.checkRole(identifier);
+
+ Long metalakeId =
+ MetalakeMetaService.getInstance().getMetalakeIdByName(identifier.namespace().level(0));
+ RolePO rolePO = getRolePOByMetalakeIdAndName(metalakeId, identifier.name(), true);
+ RoleEntity role =
+ POConverters.fromRolePO(rolePO, listSecurableObjects(rolePO), identifier.namespace());
+
+ deleteRoleWithVersion(identifier, rolePO);
+ return role;
+ }
+
/**
* Deletes the role whose version matches {@code observedRolePO}, together with its role and owner
* relations. Package-private so tests can hand in a deliberately stale PO; callers outside this
@@ -414,10 +501,12 @@ public class RoleMetaService {
*
* @param identifier the role being deleted, used only to build the error
* @param observedRolePO the role row the caller observed, carrying the version to match
+ * @throws InUseException if an access control policy names the role
*/
void deleteRoleWithVersion(NameIdentifier identifier, RolePO observedRolePO) {
Long roleId = observedRolePO.getRoleId();
SessionUtils.doMultipleWithCommit(
+ () -> lockUnreferencedRole(identifier, observedRolePO),
() ->
OccWriteSupport.deleteWithVersion(
() ->
@@ -613,9 +702,48 @@ public class RoleMetaService {
RoleMetaMapper.class,
mapper -> mapper.selectRoleMetaByIdForUpdate(observedRolePO.getRoleId())),
null,
- current ->
- Objects.equals(current.getRoleName(), observedRolePO.getRoleName())
- && Objects.equals(current.getMetalakeId(), observedRolePO.getMetalakeId()));
+ current -> isSameRole(current, observedRolePO));
+ }
+
+ /**
+ * Locks the role for deletion and refuses the deletion while an access control policy names it.
+ *
+ * <p>The metalake row is locked in share mode first. That keeps the metalake name the reference
+ * lookup uses from changing until commit, and keeps the metalake, role, policy lock order. The
+ * role row is then locked exclusively, which waits for any policy write holding it (see {@link
+ * #lockRolesNamedByPolicy}), so the references read afterwards include what that write committed.
+ * The policies are not named in the error, since the caller may not be allowed to see them.
+ */
+ private void lockUnreferencedRole(NameIdentifier identifier, RolePO observedRolePO) {
+ String metalake = identifier.namespace().level(0);
+ LiveEndpointService.lockLiveEndpoint(
+ NameIdentifier.of(metalake),
+ Entity.EntityType.METALAKE,
+ new NamespacedEntityId(observedRolePO.getMetalakeId()));
+
+ RolePO locked =
+ SessionUtils.getWithoutCommit(
+ RoleMetaMapper.class,
+ mapper -> mapper.selectRoleMetaByIdForUpdate(observedRolePO.getRoleId()));
+ if (locked == null || !isSameRole(locked, observedRolePO)) {
+ throw roleWriteFailure(identifier, observedRolePO);
+ }
+
+ // Read the references only now, past the lock, and from the database rather than the cache.
+ SessionUtils.clearSessionCache();
+ boolean referenced =
+ !SessionUtils.getWithoutCommit(
+ PolicyRoleRelMapper.class,
+ mapper -> mapper.listByRoleName(metalake, locked.getRoleName()))
+ .isEmpty();
+ if (referenced) {
+ throw new InUseException(AuthorizationUtils.ROLE_IN_USE_MSG, identifier.name(), metalake);
+ }
+ }
+
+ private static boolean isSameRole(RolePO current, RolePO observed) {
+ return Objects.equals(current.getRoleName(), observed.getRoleName())
+ && Objects.equals(current.getMetalakeId(), observed.getMetalakeId());
}
private static MetadataObject.Type getType(String type) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
index 5b6907877c..90e272ab6b 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
@@ -22,6 +22,7 @@ package org.apache.gravitino.storage.relational.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.time.Instant;
@@ -30,6 +31,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
@@ -1662,19 +1664,8 @@ public class POConverters {
*/
public static List<PolicyRoleRelPO> initializePolicyRoleRelPOs(
Long policyId, PolicyEntity policyEntity) {
- PolicyContent content = policyEntity.content();
- if (!(content instanceof AccessControlContent)) {
- return ImmutableList.of();
- }
-
ImmutableList.Builder<PolicyRoleRelPO> relations = ImmutableList.builder();
- for (String roleName :
- new LinkedHashSet<>(((AccessControlContent) content).applicableRoles())) {
- EntityFieldLimits.checkMaxLength(
- roleName,
- EntityFieldLimits.MAX_NAME_LENGTH,
- "applicable role name",
- Entity.EntityType.POLICY);
+ for (String roleName : policyRoleNames(policyEntity)) {
relations.add(
PolicyRoleRelPO.builder()
.withPolicyId(policyId)
@@ -1687,6 +1678,31 @@ public class POConverters {
return relations.build();
}
+ /**
+ * Returns the role names a policy's content names, in content order and without exact duplicates.
+ * See {@link #initializePolicyRoleRelPOs} for how names are validated.
+ *
+ * @param policyEntity the policy being written
+ * @return the role names, empty for content other than access control
+ * @throws IllegalArgumentException if a role name is longer than a role name can be
+ */
+ public static Set<String> policyRoleNames(PolicyEntity policyEntity) {
+ PolicyContent content = policyEntity.content();
+ if (!(content instanceof AccessControlContent)) {
+ return ImmutableSet.of();
+ }
+
+ Set<String> roleNames = new LinkedHashSet<>(((AccessControlContent) content).applicableRoles());
+ for (String roleName : roleNames) {
+ EntityFieldLimits.checkMaxLength(
+ roleName,
+ EntityFieldLimits.MAX_NAME_LENGTH,
+ "applicable role name",
+ Entity.EntityType.POLICY);
+ }
+ return Collections.unmodifiableSet(roleNames);
+ }
+
public static OwnerRelPO initializeOwnerRelPOsWithVersion(
Long metalakeId,
String ownerType,
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
index 427de8ba35..f8fc729568 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
@@ -46,8 +46,11 @@ import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -67,6 +70,7 @@ import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.EntityStoreFactory;
import org.apache.gravitino.GravitinoEnv;
@@ -82,6 +86,7 @@ import org.apache.gravitino.catalog.CatalogTestUtils;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.exceptions.GroupAlreadyExistsException;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.MetalakeNotInUseException;
import org.apache.gravitino.exceptions.NoSuchGroupException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
@@ -93,8 +98,12 @@ import org.apache.gravitino.lock.LockManager;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContents;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -609,6 +618,87 @@ public class TestAccessControlManager {
Assertions.assertTrue(results.get(1).error().get() instanceof NoSuchRoleException);
}
+ @Test
+ public void testDeleteRoleNamedByPolicyIsRefusedBeforePlugins() throws Exception {
+ accessControlManager.createRole(
+ METALAKE,
+ "policy_role",
+ ImmutableMap.of(),
+ Lists.newArrayList(
+ SecurableObjects.ofCatalog(
+ "catalog", Lists.newArrayList(Privileges.UseCatalog.allow()))));
+ PolicyEntity policy =
+ PolicyEntity.builder()
+ .withId(new RandomIdGenerator().nextId())
+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE))
+ .withName("policy_role_reader")
+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+ .withComment("")
+ .withEnabled(true)
+ .withContent(
+ PolicyContents.accessControl(
+ Collections.singletonList(Privilege.Name.SELECT_TABLE),
+ Collections.singletonList("policy_role")))
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build();
+ // Writing a policy also creates its hidden tag, which takes an ID from the environment.
+ Object previousIdGenerator =
+ FieldUtils.readField(GravitinoEnv.getInstance(), "idGenerator", true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "idGenerator", new RandomIdGenerator(), true);
+ try {
+ entityStore.put(policy, false);
+ reset(authorizationPlugin);
+
+ Assertions.assertThrows(
+ InUseException.class, () -> accessControlManager.deleteRole(METALAKE, "policy_role"));
+ BulkItemResult<String> bulkResult =
+ accessControlManager.deleteRoles(METALAKE, Lists.newArrayList("policy_role")).get(0);
+ Assertions.assertFalse(bulkResult.succeeded());
+ Assertions.assertInstanceOf(InUseException.class, bulkResult.error().orElse(null));
+
+ // The reference check refused first, so the plugins must still have the role.
+ verify(authorizationPlugin, never()).onRoleDeleted(any());
+ Assertions.assertEquals(
+ "policy_role", accessControlManager.getRole(METALAKE, "policy_role").name());
+
+ entityStore.delete(policy.nameIdentifier(), Entity.EntityType.POLICY);
+ Assertions.assertTrue(accessControlManager.deleteRole(METALAKE, "policy_role"));
+ verify(authorizationPlugin).onRoleDeleted(any());
+ } finally {
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "idGenerator", previousIdGenerator, true);
+ }
+ }
+
+ @Test
+ public void testRoleDeletionRetriesPluginsAfterAFailure() {
+ accessControlManager.createRole(
+ METALAKE,
+ "plugin_retry_role",
+ ImmutableMap.of(),
+ Lists.newArrayList(
+ SecurableObjects.ofCatalog(
+ "catalog", Lists.newArrayList(Privileges.UseCatalog.allow()))));
+ reset(authorizationPlugin);
+ doThrow(new RuntimeException("plugin unavailable"))
+ .doReturn(true)
+ .when(authorizationPlugin)
+ .onRoleDeleted(any());
+
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> accessControlManager.deleteRole(METALAKE, "plugin_retry_role"));
+ // The plugin failed before the store delete, so the role is still there to retry.
+ Assertions.assertEquals(
+ "plugin_retry_role", accessControlManager.getRole(METALAKE, "plugin_retry_role").name());
+
+ Assertions.assertTrue(accessControlManager.deleteRole(METALAKE, "plugin_retry_role"));
+ verify(authorizationPlugin, times(2)).onRoleDeleted(any());
+ Assertions.assertThrows(
+ NoSuchRoleException.class,
+ () -> accessControlManager.getRole(METALAKE, "plugin_retry_role"));
+ }
+
@Test
public void testListRoles() {
Map<String, String> props = ImmutableMap.of("k1", "v1");
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java
index ae2f981ad3..1dcc5e8efa 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java
@@ -40,7 +40,9 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.meta.RoleEntity;
import org.apache.gravitino.policy.Policy;
@@ -50,7 +52,6 @@ import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;
import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
-import org.apache.gravitino.storage.relational.session.SqlSessions;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.ibatis.session.SqlSession;
@@ -65,6 +66,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testReferencesFollowPolicyContent() throws IOException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor", "steward");
PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));
backend.insert(policy, false);
@@ -86,6 +88,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testOverwriteAttachesReferencesToTheSurvivingPolicyRow() throws IOException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity original = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(original, false);
@@ -102,6 +105,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testFailedPolicyWriteLeavesNoReferences() throws IOException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "steward");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
@@ -140,6 +144,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
public void testRoleNameAtTheLengthLimitIsAccepted() throws IOException {
createAndInsertMakeLake(METALAKE);
String longestRoleName = "r".repeat(EntityFieldLimits.MAX_NAME_LENGTH);
+ createRoles(METALAKE, longestRoleName);
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList(longestRoleName));
backend.insert(policy, false);
@@ -149,6 +154,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testFailedReferenceUpdateKeepsThePreviousPolicy() throws IOException, SQLException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
String versionsOfPolicy = "SELECT COUNT(*) FROM policy_version_info WHERE policy_id = ?";
@@ -175,6 +181,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testDuplicateRoleNamesCollapseToOneReference() throws IOException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst");
PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "analyst"));
backend.insert(policy, false);
@@ -228,6 +235,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testPolicyDeleteClearsReferences() throws IOException, SQLException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
@@ -241,6 +249,8 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
createAndInsertMakeLake(METALAKE);
String otherMetalake = METALAKE + "_other";
createAndInsertMakeLake(otherMetalake);
+ createRoles(METALAKE, "analyst");
+ createRoles(otherMetalake, "analyst");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
@@ -260,6 +270,8 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
createAndInsertMakeLake(METALAKE);
String otherMetalake = METALAKE + "_other";
createAndInsertMakeLake(otherMetalake);
+ createRoles(METALAKE, "analyst");
+ createRoles(otherMetalake, "analyst");
backend.insert(accessControlPolicy("reader", Collections.singletonList("analyst")), false);
backend.insert(
accessControlPolicy(otherMetalake, "writer", Collections.singletonList("analyst")), false);
@@ -295,6 +307,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testUpdateReadBeforeMetalakeDeleteFailsWithoutReferences() throws Exception {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
@@ -322,6 +335,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
@TestTemplate
public void testSupersededReferencesLeaveNoTombstone() throws IOException, SQLException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity policy = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));
backend.insert(policy, false);
@@ -345,6 +359,7 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
public void testLegacyCleanupRemovesOnlyReferencesOfDeletedPolicies()
throws IOException, SQLException {
createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity deleted = accessControlPolicy("reader", Arrays.asList("analyst", "auditor"));
PolicyEntity live = accessControlPolicy("writer", Collections.singletonList("analyst"));
backend.insert(deleted, false);
@@ -368,23 +383,28 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
}
/**
- * Holds a policy row the way an in-flight update does, waits until the metalake delete is blocked
- * on that row, and only then lets the update add a reference and commit.
+ * Holds the metalake row the way an in-flight policy update does, waits until the metalake delete
+ * is blocked on that row, and only then lets the update add a reference and commit.
*
- * <p>The delete clears that reference only if its reference cleanup runs after the policy delete
- * it was blocked on. With the cleanup ordered first, it has already run by the time the update
- * commits, and the new reference is left active.
+ * <p>A policy update locks the metalake before the roles it names and its own row, the order the
+ * metalake delete locks them in. The delete therefore cannot run any of its cleanup until the
+ * update commits, and then clears the reference the update added.
*/
private void assertMetalakeDeleteClearsReferenceAddedWhileWaiting(boolean cascade)
throws Exception {
- createAndInsertMakeLake(METALAKE);
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE);
+ createRoles(METALAKE, "analyst", "auditor");
PolicyEntity policy = accessControlPolicy("reader", Collections.singletonList("analyst"));
backend.insert(policy, false);
Throwable deleteFailure =
new TransactionLockWaits(backendType)
.whileTransactionHeld(
- () -> lockPolicyRow(policy.id()),
+ () ->
+ LiveEndpointService.lockLiveEndpoint(
+ NameIdentifier.of(METALAKE),
+ Entity.EntityType.METALAKE,
+ new NamespacedEntityId(metalake.id())),
() ->
backend.delete(
NameIdentifier.of(METALAKE), Entity.EntityType.METALAKE, cascade),
@@ -420,17 +440,18 @@ public class TestPolicyRoleRelService extends TestJDBCBackend {
}
}
- /** Takes the policy row lock in the current transaction, which an update holds until commit. */
- private void lockPolicyRow(long policyId) throws SQLException {
- SqlSession session = SqlSessions.getSqlSession();
- try (PreparedStatement lock =
- session
- .getConnection()
- .prepareStatement("SELECT policy_id FROM policy_meta WHERE policy_id = ? FOR UPDATE")) {
- lock.setLong(1, policyId);
- lock.executeQuery().close();
- } finally {
- SqlSessions.closeSqlSession();
+ /** Creates live roles, without privileges, for policies to name. */
+ private void createRoles(String metalake, String... roleNames) throws IOException {
+ for (String roleName : roleNames) {
+ backend.insert(
+ createRoleEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ AuthorizationUtils.ofRoleNamespace(metalake),
+ roleName,
+ AUDIT_INFO,
+ Collections.emptyList(),
+ null),
+ false);
}
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestReferencedRoleDeletion.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestReferencedRoleDeletion.java
new file mode 100644
index 0000000000..370bddbc35
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestReferencedRoleDeletion.java
@@ -0,0 +1,576 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+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.NameIdentifier;
+import org.apache.gravitino.authorization.AccessControlManager;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.bulk.BulkItemResult;
+import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.exceptions.IllegalRoleException;
+import org.apache.gravitino.exceptions.InUseException;
+import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContent;
+import org.apache.gravitino.policy.PolicyContents;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;
+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.function.Executable;
+import org.mockito.Mockito;
+
+/**
+ * Tests that a role cannot be deleted while an access control policy names it, and that a policy
+ * cannot name a role that does not exist.
+ *
+ * <p>The two-transaction tests hold one write open until the other is waiting on it, then commit,
+ * so each covers one commit order between a policy write and a role deletion.
+ */
+public class TestReferencedRoleDeletion extends TestJDBCBackend {
+
+ private static final String METALAKE = "referenced_role_metalake";
+
+ private static LockManager lockManager;
+
+ private Object previousLockManager;
+ private Object previousCatalogManager;
+ private AccessControlManager accessControlManager;
+
+ @BeforeEach
+ void setUpAccessControl() throws IllegalAccessException {
+ Config config = new Config(false) {};
+ config.set(Configs.SERVICE_ADMINS, Collections.singletonList("admin"));
+ // Bulk deletion takes the in-memory tree lock before it deletes each role.
+ if (lockManager == null) {
+ lockManager = new LockManager(config);
+ }
+ previousLockManager = FieldUtils.readField(GravitinoEnv.getInstance(), "lockManager", true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", lockManager, true);
+ // A deleted role is passed to the catalogs' authorization plugins. These roles hold no
+ // privileges, so no catalog is consulted, but the lookup needs a catalog manager to exist.
+ previousCatalogManager =
+ FieldUtils.readField(GravitinoEnv.getInstance(), "catalogManager", true);
+ FieldUtils.writeField(
+ GravitinoEnv.getInstance(), "catalogManager", Mockito.mock(CatalogManager.class), true);
+ accessControlManager =
+ new AccessControlManager(
+ RelationalEntityStore.forOfflineMigration(backend, config),
+ RandomIdGenerator.INSTANCE,
+ config);
+ }
+
+ @AfterEach
+ void restoreEnvironment() throws IllegalAccessException {
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", previousLockManager, true);
+ FieldUtils.writeField(
+ GravitinoEnv.getInstance(), "catalogManager", previousCatalogManager, true);
+ }
+
+ @TestTemplate
+ public void testPolicyCannotNameMissingRole() throws IOException, SQLException {
+ createAndInsertMakeLake(METALAKE);
+ PolicyEntity policy = policy("reader", "analyst");
+
+ for (boolean overwritten : new boolean[] {false, true}) {
+ IllegalRoleException failure =
+ Assertions.assertThrows(
+ IllegalRoleException.class, () -> backend.insert(policy, overwritten));
+ Assertions.assertTrue(failure.getMessage().contains("analyst"), failure.getMessage());
+ }
+
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_meta", policy.id()));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_version_info", policy.id()));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_role_relation_meta", policy.id()));
+ }
+
+ @TestTemplate
+ public void testPolicyCannotNameRoleWithTrailingSpace() throws IOException, SQLException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ // MySQL's collation finds "analyst" for "analyst "; every backend must still refuse it.
+ PolicyEntity padded = policy("padded", "analyst ");
+
+ Assertions.assertThrows(IllegalRoleException.class, () -> backend.insert(padded, false));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_meta", padded.id()));
+
+ PolicyEntity policy = policy("reader", "analyst");
+ backend.insert(policy, false);
+ Assertions.assertThrows(IllegalRoleException.class, () -> updateRoles(policy, "analyst "));
+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testPolicyUpdateCannotNameMissingRole() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ PolicyEntity policy = policy("reader", "analyst");
+ backend.insert(policy, false);
+ int versionsBefore = countPolicyRows("policy_version_info", policy.id());
+
+ Assertions.assertThrows(
+ IllegalRoleException.class, () -> updateRoles(policy, "analyst", "auditor"));
+
+ PolicyEntity stored = backend.get(policy.nameIdentifier(), Entity.EntityType.POLICY);
+ Assertions.assertEquals(policy.content(), stored.content());
+ Assertions.assertEquals(versionsBefore, countPolicyRows("policy_version_info", policy.id()));
+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testDeletingReferencedRoleIsRefused() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ backend.insert(policy("reader", "analyst"), false);
+
+ InUseException failure =
+ Assertions.assertThrows(InUseException.class, () -> deleteRole("analyst"));
+
+ Assertions.assertTrue(failure.getMessage().contains("analyst"), failure.getMessage());
+ // The caller may not be allowed to see the policy, so the error does not name it.
+ Assertions.assertFalse(failure.getMessage().contains("reader"), failure.getMessage());
+ Assertions.assertTrue(roleExists("analyst"));
+ }
+
+ @TestTemplate
+ public void testBulkDeletionRefusesOnlyReferencedRoles() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst", "auditor");
+ backend.insert(policy("reader", "analyst"), false);
+
+ List<BulkItemResult<String>> results =
+ accessControlManager.deleteRoles(METALAKE, Arrays.asList("analyst", "auditor"));
+
+ assertRefused(results.get(0));
+ assertSucceeded(results.get(1));
+ Assertions.assertTrue(roleExists("analyst"));
+ Assertions.assertFalse(roleExists("auditor"));
+ }
+
+ @TestTemplate
+ public void testRoleCanBeDeletedOnceNoPolicyNamesIt() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst", "auditor");
+ PolicyEntity reader = policy("reader", "analyst");
+ PolicyEntity writer = policy("writer", "analyst");
+ backend.insert(reader, false);
+ backend.insert(writer, false);
+
+ updateRoles(reader, "auditor");
+ Assertions.assertThrows(InUseException.class, () -> deleteRole("analyst"));
+
+ Assertions.assertTrue(backend.delete(writer.nameIdentifier(), Entity.EntityType.POLICY, false));
+ Assertions.assertTrue(deleteRole("analyst"));
+ Assertions.assertFalse(roleExists("analyst"));
+ }
+
+ @TestTemplate
+ public void testReferenceInAnotherMetalakeDoesNotBlockDeletion() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ String otherMetalake = METALAKE + "_other";
+ createAndInsertMakeLake(otherMetalake);
+ createRoles("analyst");
+ createRolesIn(otherMetalake, "analyst");
+ backend.insert(policyIn(otherMetalake, "reader", "analyst"), false);
+
+ Assertions.assertTrue(deleteRole("analyst"));
+ Assertions.assertThrows(
+ InUseException.class,
+ () ->
+ backend.delete(
+ AuthorizationUtils.ofRole(otherMetalake, "analyst"),
+ Entity.EntityType.ROLE,
+ false));
+ }
+
+ @TestTemplate
+ public void testMetalakeDeleteIsNotBlockedByReferences() throws IOException {
+ for (boolean cascade : new boolean[] {true, false}) {
+ String metalake = METALAKE + (cascade ? "_cascade" : "_plain");
+ createAndInsertMakeLake(metalake);
+ createRolesIn(metalake, "analyst");
+ PolicyEntity policy = policyIn(metalake, "reader", "analyst");
+ backend.insert(policy, false);
+
+ Assertions.assertTrue(
+ backend.delete(NameIdentifier.of(metalake), Entity.EntityType.METALAKE, cascade));
+
+ Assertions.assertEquals(0, countPolicyRows("policy_meta", policy.id()));
+ Assertions.assertEquals(0, countPolicyRows("policy_role_relation_meta", policy.id()));
+ Assertions.assertEquals(
+ 0, countActiveRowsWhere("role_meta", String.format("role_name = '%s'", "analyst")));
+ }
+ }
+
+ @TestTemplate
+ public void testDeletionWaitingOnPolicyCreateIsRefused() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ PolicyEntity policy = policy("reader", "analyst");
+
+ Throwable failure = whileHeld(() -> backend.insert(policy, false), () -> deleteRole("analyst"));
+
+ Assertions.assertInstanceOf(InUseException.class, failure);
+ Assertions.assertTrue(roleExists("analyst"));
+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testDeletionWaitingOnPolicyUpdateIsRefused() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst", "auditor");
+ PolicyEntity policy = policy("reader", "auditor");
+ backend.insert(policy, false);
+
+ Throwable failure =
+ whileHeld(() -> updateRoles(policy, "auditor", "analyst"), () -> deleteRole("analyst"));
+
+ Assertions.assertInstanceOf(InUseException.class, failure);
+ Assertions.assertTrue(roleExists("analyst"));
+ Assertions.assertEquals(Arrays.asList("analyst", "auditor"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testUpdatesToPoliciesNamingNoRolesDoNotWaitOnEachOther() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ PolicyEntity first =
+ createPolicy(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofPolicy(METALAKE),
+ "first",
+ AUDIT_INFO);
+ PolicyEntity second =
+ createPolicy(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofPolicy(METALAKE),
+ "second",
+ AUDIT_INFO);
+ backend.insert(first, false);
+ backend.insert(second, false);
+
+ // Only an update naming roles takes the metalake lock, which H2 takes exclusively.
+ Throwable failure =
+ new TransactionLockWaits(backendType)
+ .whileTransactionOpen(
+ () -> updateComment(first, "edited"), () -> updateComment(second, "edited"));
+
+ Assertions.assertNull(failure);
+ PolicyEntity stored = backend.get(second.nameIdentifier(), Entity.EntityType.POLICY);
+ Assertions.assertEquals("edited", stored.comment());
+ }
+
+ @TestTemplate
+ public void testDeletionRefusedAfterWaitingNeverRunsItsCleanup() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ PolicyEntity policy = policy("reader", "analyst");
+ // Stands in for the authorization plugins, which RoleManager runs as this cleanup.
+ List<String> cleanedUp = new CopyOnWriteArrayList<>();
+
+ Throwable failure =
+ whileHeld(
+ () -> backend.insert(policy, false),
+ () ->
+ backend.deleteAndGet(
+ AuthorizationUtils.ofRole(METALAKE, "analyst"),
+ Entity.EntityType.ROLE,
+ RoleEntity.class,
+ role -> cleanedUp.add(role.name())));
+
+ Assertions.assertInstanceOf(InUseException.class, failure);
+ Assertions.assertEquals(Collections.emptyList(), cleanedUp);
+ Assertions.assertTrue(roleExists("analyst"));
+ }
+
+ @TestTemplate
+ public void testFailedCleanupKeepsTheRole() throws IOException {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ NameIdentifier analyst = AuthorizationUtils.ofRole(METALAKE, "analyst");
+
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ backend.deleteAndGet(
+ analyst,
+ Entity.EntityType.ROLE,
+ RoleEntity.class,
+ role -> {
+ throw new IllegalStateException("plugin unavailable");
+ }));
+ Assertions.assertTrue(roleExists("analyst"));
+
+ List<String> cleanedUp = new CopyOnWriteArrayList<>();
+ Assertions.assertTrue(
+ backend
+ .deleteAndGet(
+ analyst,
+ Entity.EntityType.ROLE,
+ RoleEntity.class,
+ role -> cleanedUp.add(role.name()))
+ .isPresent());
+ Assertions.assertEquals(Collections.singletonList("analyst"), cleanedUp);
+ Assertions.assertFalse(roleExists("analyst"));
+ }
+
+ @TestTemplate
+ public void testBulkDeletionWaitingOnPolicyWriteIsRefused() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst", "auditor");
+ PolicyEntity policy = policy("reader", "analyst");
+ AtomicReference<List<BulkItemResult<String>>> results = new AtomicReference<>();
+
+ Throwable failure =
+ whileHeld(
+ () -> backend.insert(policy, false),
+ () ->
+ results.set(
+ accessControlManager.deleteRoles(
+ METALAKE, Arrays.asList("analyst", "auditor"))));
+
+ Assertions.assertNull(failure);
+ assertRefused(results.get().get(0));
+ assertSucceeded(results.get().get(1));
+ Assertions.assertTrue(roleExists("analyst"));
+ Assertions.assertFalse(roleExists("auditor"));
+ Assertions.assertEquals(Collections.singletonList("analyst"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testPolicyCreateWaitingOnDeletionFails() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ PolicyEntity policy = policy("reader", "analyst");
+
+ Throwable failure =
+ whileHeld(
+ () -> Assertions.assertTrue(deleteRole("analyst")),
+ () -> backend.insert(policy, false));
+
+ Assertions.assertInstanceOf(IllegalRoleException.class, failure);
+ Assertions.assertFalse(roleExists("analyst"));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_meta", policy.id()));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_version_info", policy.id()));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_role_relation_meta", policy.id()));
+ }
+
+ @TestTemplate
+ public void testPolicyUpdateWaitingOnDeletionFails() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst", "auditor");
+ PolicyEntity policy = policy("reader", "auditor");
+ backend.insert(policy, false);
+ int versionsBefore = countPolicyRows("policy_version_info", policy.id());
+
+ Throwable failure =
+ whileHeld(
+ () -> Assertions.assertTrue(deleteRole("analyst")),
+ () -> updateRoles(policy, "auditor", "analyst"));
+
+ Assertions.assertInstanceOf(IllegalRoleException.class, failure);
+ Assertions.assertFalse(roleExists("analyst"));
+ PolicyEntity stored = backend.get(policy.nameIdentifier(), Entity.EntityType.POLICY);
+ Assertions.assertEquals(policy.content(), stored.content());
+ Assertions.assertEquals(versionsBefore, countPolicyRows("policy_version_info", policy.id()));
+ Assertions.assertEquals(Collections.singletonList("auditor"), rolesOf(policy.id()));
+ }
+
+ @TestTemplate
+ public void testPolicyWriteWaitingOnBulkDeletionFails() throws Exception {
+ createAndInsertMakeLake(METALAKE);
+ createRoles("analyst");
+ PolicyEntity policy = policy("reader", "analyst");
+
+ Throwable failure =
+ whileHeld(
+ () ->
+ assertSucceeded(
+ accessControlManager
+ .deleteRoles(METALAKE, Collections.singletonList("analyst"))
+ .get(0)),
+ () -> backend.insert(policy, false));
+
+ Assertions.assertInstanceOf(IllegalRoleException.class, failure);
+ Assertions.assertFalse(roleExists("analyst"));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_meta", policy.id()));
+ Assertions.assertEquals(0L, countAllPolicyRows("policy_role_relation_meta", policy.id()));
+ }
+
+ /**
+ * Runs {@code first} in a transaction, starts {@code second} in another one, waits until the
+ * database reports {@code second} waiting on {@code first}, and then commits {@code first}.
+ *
+ * @return the failure of {@code second}, or null if it committed
+ */
+ private Throwable whileHeld(Executable first, Executable second) throws Exception {
+ return new TransactionLockWaits(backendType)
+ .whileTransactionHeld(first, second, () -> {}, true);
+ }
+
+ private static void assertSucceeded(BulkItemResult<String> result) {
+ Assertions.assertTrue(
+ result.succeeded(), () -> "Unexpected failure: " + result.error().orElse(null));
+ }
+
+ private static void assertRefused(BulkItemResult<String> result) {
+ Assertions.assertFalse(result.succeeded());
+ Assertions.assertInstanceOf(InUseException.class, result.error().orElse(null));
+ }
+
+ private boolean deleteRole(String roleName) throws IOException {
+ return backend.delete(
+ AuthorizationUtils.ofRole(METALAKE, roleName), Entity.EntityType.ROLE, false);
+ }
+
+ private boolean roleExists(String roleName) throws IOException {
+ return backend.exists(AuthorizationUtils.ofRole(METALAKE, roleName), Entity.EntityType.ROLE);
+ }
+
+ private void createRoles(String... roleNames) throws IOException {
+ createRolesIn(METALAKE, roleNames);
+ }
+
+ private void createRolesIn(String metalake, String... roleNames) throws IOException {
+ for (String roleName : roleNames) {
+ backend.insert(
+ createRoleEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ AuthorizationUtils.ofRoleNamespace(metalake),
+ roleName,
+ AUDIT_INFO,
+ Collections.emptyList(),
+ null),
+ false);
+ }
+ }
+
+ private void updateRoles(PolicyEntity policy, String... roleNames) throws IOException {
+ backend.update(
+ policy.nameIdentifier(),
+ Entity.EntityType.POLICY,
+ entity -> withRoles(policy, Arrays.asList(roleNames)));
+ }
+
+ private PolicyEntity policy(String name, String... roleNames) {
+ return policyIn(METALAKE, name, roleNames);
+ }
+
+ private PolicyEntity policyIn(String metalake, String name, String... roleNames) {
+ return PolicyEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withNamespace(NamespaceUtil.ofPolicy(metalake))
+ .withName(name)
+ .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+ .withComment("")
+ .withEnabled(true)
+ .withContent(accessControl(Arrays.asList(roleNames)))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
+ private void updateComment(PolicyEntity policy, String comment) throws IOException {
+ backend.update(
+ policy.nameIdentifier(),
+ Entity.EntityType.POLICY,
+ entity ->
+ PolicyEntity.builder()
+ .withId(policy.id())
+ .withNamespace(policy.namespace())
+ .withName(policy.name())
+ .withPolicyType(policy.policyType())
+ .withComment(comment)
+ .withEnabled(policy.enabled())
+ .withContent(policy.content())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ }
+
+ private static PolicyEntity withRoles(PolicyEntity policy, List<String> roleNames) {
+ return PolicyEntity.builder()
+ .withId(policy.id())
+ .withNamespace(policy.namespace())
+ .withName(policy.name())
+ .withPolicyType(policy.policyType())
+ .withComment(policy.comment())
+ .withEnabled(policy.enabled())
+ .withContent(accessControl(roleNames))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
+ private static PolicyContent accessControl(List<String> roleNames) {
+ return PolicyContents.accessControl(
+ Collections.singletonList(Privilege.Name.SELECT_TABLE), roleNames);
+ }
+
+ private List<String> rolesOf(long policyId) {
+ return SessionUtils.getWithoutCommit(
+ PolicyRoleRelMapper.class, mapper -> mapper.listByPolicyId(policyId))
+ .stream()
+ .map(PolicyRoleRelPO::getRoleName)
+ .collect(Collectors.toList());
+ }
+
+ private int countPolicyRows(String table, long policyId) {
+ return countActiveRowsWhere(table, "policy_id = " + policyId);
+ }
+
+ /** Counts rows whether live or soft-deleted, for writes that must have committed nothing. */
+ private long countAllPolicyRows(String table, long policyId) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ PreparedStatement statement =
+ connection.prepareStatement("SELECT COUNT(*) FROM " + table + " WHERE policy_id = ?")) {
+ statement.setLong(1, policyId);
+ try (ResultSet rows = statement.executeQuery()) {
+ Assertions.assertTrue(rows.next());
+ return rows.getLong(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 9b16109eb8..8953ebb1fa 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
@@ -176,6 +176,15 @@ public class TestTagMetaService extends TestJDBCBackend {
service.associateTagsWithMetadataObject(
catalog.nameIdentifier(), catalog.type(), added, removed));
}
+ // An access control policy must name an existing role.
+ backend.insert(
+ createRoleEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),
+ "reader",
+ AUDIT_INFO,
+ "catalog"),
+ false);
PolicyEntity policy =
PolicyEntity.builder()
.withId(RandomIdGenerator.INSTANCE.nextId())
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java
index bb526dab56..33d2300e6a 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TransactionLockWaits.java
@@ -87,6 +87,31 @@ final class TransactionLockWaits {
}
}
+ /**
+ * Runs {@code holder} in a transaction on the calling thread, then runs {@code contender} in its
+ * own transaction on another thread while the holder is still open. The holder is rolled back
+ * only after the contender has finished, so a contender that waits on the holder times out.
+ *
+ * @param holder the work whose transaction stays open
+ * @param contender the work that must not wait for the holder
+ * @return the contender's failure, or null if its transaction committed
+ * @throws Exception if the contender waits on the holder, or the holder fails
+ */
+ Throwable whileTransactionOpen(Executable holder, Executable contender) throws Exception {
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ SessionUtils.beginTransaction();
+ try {
+ prepareTransaction();
+ Assertions.assertDoesNotThrow(holder);
+ return submitTransaction(executor, new CompletableFuture<>(), contender)
+ .get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ } finally {
+ SessionUtils.rollbackTransaction();
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ }
+ }
+
/**
* Runs {@code operation} in its own transaction on {@code executor}.
*
diff --git a/docs/open-api/bulk.yaml b/docs/open-api/bulk.yaml
index 353203cdde..b211ce63b5 100644
--- a/docs/open-api/bulk.yaml
+++ b/docs/open-api/bulk.yaml
@@ -238,7 +238,7 @@ paths:
- access control
summary: Remove roles in bulk
operationId: bulkRemoveRoles
- description: Removes roles in best-effort mode. Failed items are returned in the top-level errors array. Role names in the same request must be unique. The maximum request size is controlled by `gravitino.server.bulk.maxItems`, which defaults to 100.
+ description: Removes roles in best-effort mode. Failed items are returned in the top-level errors array. A role that an access control policy names is not removed; its error has code 1010 (`InUseException`). Role names in the same request must be unique. The maximum request size is controlled by `gravitino.server.bulk.maxItems`, which defaults to 100.
requestBody:
content:
application/json:
diff --git a/docs/open-api/roles.yaml b/docs/open-api/roles.yaml
index 63dea88d53..709a0eab46 100644
--- a/docs/open-api/roles.yaml
+++ b/docs/open-api/roles.yaml
@@ -137,11 +137,21 @@ paths:
- access control
summary: Delete role
operationId: deleteRole
+ description: Deletes a role. A role that an access control policy names cannot be deleted; remove it from those policies first.
responses:
"200":
$ref: "./openapi.yaml#/components/responses/DeleteResponse"
"400":
$ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"
+ "409":
+ description: Conflict - An access control policy names the role
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ examples:
+ RoleInUseException:
+ $ref: "#/components/examples/RoleInUseException"
"5xx":
$ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
@@ -402,6 +412,17 @@ components:
]
}
+ RoleInUseException:
+ value: {
+ "code": 1010,
+ "type": "InUseException",
+ "message": "Role role1 in metalake metalake1 is referenced by access control policies; remove it from those policies before deleting it",
+ "stack": [
+ "org.apache.gravitino.exceptions.InUseException: Role role1 in metalake metalake1 is referenced by access control policies; remove it from those policies before deleting it",
+ "..."
+ ]
+ }
+
IllegalMetadataObjectException:
value: {
"code": 1001,
diff --git a/docs/policies.md b/docs/policies.md
index 4eca76b77e..722b13e6f8 100644
--- a/docs/policies.md
+++ b/docs/policies.md
@@ -59,6 +59,10 @@ by the experimental Iceberg REST service. Compatible readers enforce those restr
stable service does not load the experimental provider by default. Access-control policy
enforcement remains separate.
+An access control policy can name only roles that exist in its metalake; creating or updating one
+that names a missing role fails. While a policy names a role, that role cannot be deleted. Remove it
+from the policy first.
+
### Read-Restriction Expressions
Row-filter and column-mask expressions use `restricted-sql-v1`. A complete definition declares
diff --git a/docs/security/access-control.md b/docs/security/access-control.md
index 5fb2583d75..61bdb2aaf7 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -140,6 +140,11 @@ A role holds objects, and for each one a list of privileges, each carrying an `A
condition. A privilege binds only to object types it supports, so `CREATE_TABLE` binds to a metalake,
catalog, or schema, never to a table. Whoever creates a role owns it, and can alter or delete it.
+A role cannot be deleted while an access control policy names it in its applicable roles. Remove
+the role from those policies, or delete them, first. The deletion fails with `InUseException`
+(HTTP 409); in a bulk delete, only that role's item fails. Deleting the metalake removes its roles
+and policies together and is not blocked.
+
#### Ownership
Ownership can be held by a group as well as a user, in which case every member of that group holds
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
index bd99aa19b3..657d507fb1 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
@@ -686,6 +686,9 @@ public class ExceptionHandlers {
} else if (e instanceof NotInUseException) {
return Utils.notInUse(errorMsg, e);
+ } else if (e instanceof InUseException) {
+ return Utils.inUse(errorMsg, e);
+
} else {
return super.handle(op, role, metalake, e);
}
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
index 8affa25541..6cac9549ad 100644
--- 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
@@ -114,6 +114,8 @@ import org.mockito.stubbing.Answer;
/** Verifies tag assignment authorization against persisted H2 metadata. */
@Tag("server-tag-assignment-h2-test")
public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
+ private static final String READER_ROLE = "reader";
+
@TestTemplate
void testCreatedAccessTagInvalidatesMissingTagAuthorization() throws Throwable {
String metalake = "missing_tag_auth_h2";
@@ -1223,6 +1225,8 @@ public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
RelationalEntityStore store = newStore();
PolicyManager policies = new PolicyManager(RandomIdGenerator.INSTANCE, store);
TagManager tags = new TagManager(RandomIdGenerator.INSTANCE, store);
+ // Stored before MockedSecurity, which stubs AuthorizationUtils; bound to the tag below.
+ putPolicy(store, metalake, "access", Policy.BuiltInType.ACCESS_CONTROL, selectContent());
UserPrincipal principal = new UserPrincipal("tester");
try (EnvOverride overrides = new EnvOverride();
MockedSecurity security = new MockedSecurity(principal)) {
@@ -1283,7 +1287,6 @@ public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
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()))
@@ -1326,7 +1329,7 @@ public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
}
private static PolicyContent selectContent() {
- return PolicyContents.accessControl(List.of(Privilege.Name.SELECT_TABLE), List.of("reader"));
+ return PolicyContents.accessControl(List.of(Privilege.Name.SELECT_TABLE), List.of(READER_ROLE));
}
private static PolicyEntity newPolicy(
@@ -1349,6 +1352,12 @@ public class TestTagAssignmentAuthorizationH2 extends TestJDBCBackend {
Policy.BuiltInType type,
PolicyContent content)
throws IOException {
+ if (type == Policy.BuiltInType.ACCESS_CONTROL
+ && !store.exists(
+ AuthorizationUtils.ofRole(metalake, READER_ROLE), Entity.EntityType.ROLE)) {
+ // An access control policy must name an existing role.
+ putRole(store, metalake, READER_ROLE, List.of());
+ }
PolicyEntity policy = newPolicy(metalake, name, type, content);
store.put(policy, false);
return policy;
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestBulkOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestBulkOperations.java
index 9cf6e48408..2355647294 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestBulkOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestBulkOperations.java
@@ -73,6 +73,7 @@ import org.apache.gravitino.dto.responses.BulkUserResponse;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.exceptions.GroupAlreadyExistsException;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NoSuchGroupException;
import org.apache.gravitino.exceptions.NoSuchRoleException;
import org.apache.gravitino.exceptions.NoSuchUserException;
@@ -417,6 +418,35 @@ public class TestBulkOperations extends BaseOperationsTest {
Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, bulkResponse.getErrors()[0].getCode());
}
+ @Test
+ public void testBulkRemoveRolesReportsReferencedRoleAsInUse() {
+ when(manager.deleteRoles(any(), any()))
+ .thenReturn(
+ Arrays.asList(
+ BulkItemResult.success(0, "role1"),
+ BulkItemResult.failure(
+ 1,
+ "referenced",
+ new InUseException(
+ "Role referenced is referenced by access control policies"))));
+
+ BulkRemoveRequest request = new BulkRemoveRequest(new String[] {"role1", "referenced"});
+ Response response =
+ target("/bulk/metalakes/metalake1/roles/remove")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ BulkRemoveResponse bulkResponse = response.readEntity(BulkRemoveResponse.class);
+ Assertions.assertArrayEquals(new String[] {"role1"}, bulkResponse.getNames());
+ Assertions.assertEquals(1, bulkResponse.getErrors().length);
+ Assertions.assertEquals("referenced", bulkResponse.getErrors()[0].getName());
+ Assertions.assertEquals(ErrorConstants.IN_USE_CODE, bulkResponse.getErrors()[0].getCode());
+ Assertions.assertEquals(
+ InUseException.class.getSimpleName(), bulkResponse.getErrors()[0].getType());
+ }
+
@Test
public void testRemoveUsersWithNullRequest() {
Response response =
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestRoleOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestRoleOperations.java
index 2989a48070..383f1ddab0 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestRoleOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestRoleOperations.java
@@ -71,6 +71,7 @@ import org.apache.gravitino.dto.responses.RoleResponse;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.exceptions.IllegalNamespaceException;
import org.apache.gravitino.exceptions.IllegalPrivilegeException;
+import org.apache.gravitino.exceptions.InUseException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
@@ -631,6 +632,21 @@ public class TestRoleOperations extends BaseOperationsTest {
ErrorResponse errorResponse = resp3.readEntity(ErrorResponse.class);
Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse.getCode());
Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse.getType());
+
+ // A role that an access control policy names is in use.
+ doThrow(new InUseException("Role role1 is referenced by access control policies"))
+ .when(manager)
+ .deleteRole(any(), any());
+ Response resp4 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), resp4.getStatus());
+ ErrorResponse inUseResponse = resp4.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.IN_USE_CODE, inUseResponse.getCode());
+ Assertions.assertEquals(InUseException.class.getSimpleName(), inUseResponse.getType());
}
@Test