Copilot commented on code in PR #14976: URL: https://github.com/apache/gravitino/pull/14976#discussion_r4579785545
########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); Review Comment: PermissionManager.overridePrivilegesInRole commits the full replacement, then emits per-object callbacks sharing the original role snapshot; treating each reconstructed role as the final state can delete shared ACLs when moving a grant or leave auxiliary ACLs orphaned when removing multiple topics. Compute removal candidates from the affected objects and reconcile them against the persisted post-update role, rather than substituting this partial reconstruction. Add override tests for both moving a grant and removing all grants across multiple topics. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); + + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + applyRoleUpdateForPrincipal( + Owner.Type.USER, + username, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + applyRoleUpdateForPrincipal( + Owner.Type.GROUP, + groupName, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + user.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + group.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAdded(User user) throws RuntimeException { + // External SASL/OAuth IdP manages user existence; Kafka ACLs are added on role/owner grants. + return Boolean.TRUE; + } + + @Override + public Boolean onUserRemoved(User user) throws RuntimeException { + if (user == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatUserPrincipal(user.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAcquired(User user) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAdded(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupRemoved(Group group) throws RuntimeException { + if (group == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatGroupPrincipal(group.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAcquired(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onOwnerSet( + MetadataObject metadataObject, @Nullable Owner preOwner, @Nullable Owner newOwner) + throws RuntimeException { + if (metadataObject == null || !appliesToThisCatalog(metadataObject)) { + return Boolean.TRUE; + } + + if (preOwner != null && !sameOwner(preOwner, newOwner)) { + String prePrincipal = formatOwnerPrincipal(preOwner); + Set<AclBinding> candidateRemovals = + KafkaPrivilegeMapper.ownerAclBindings(metadataObject, prePrincipal, properties); + Map<MetadataObject, Optional<Owner>> ownerOverrides = new HashMap<>(); + ownerOverrides.put(metadataObject, Optional.ofNullable(newOwner)); + removeBindingsPreservingActiveGrants( + preOwner.type(), + preOwner.name(), + candidateRemovals, + Collections.emptySet(), + Collections.emptyList(), + ownerOverrides, + null); + } + + if (newOwner != null) { + String newPrincipal = formatOwnerPrincipal(newOwner); + createAcls(KafkaPrivilegeMapper.ownerAclBindings(metadataObject, newPrincipal, properties)); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onMetadataUpdated(MetadataObjectChange... changes) throws RuntimeException { + if (changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + for (MetadataObjectChange change : changes) { + if (change instanceof MetadataObjectChange.RemoveMetadataObject) { + MetadataObject removed = + ((MetadataObjectChange.RemoveMetadataObject) change).metadataObject(); + handleMetadataRemoved(removed); + } else if (change instanceof MetadataObjectChange.RenameMetadataObject) { + MetadataObjectChange.RenameMetadataObject rename = + (MetadataObjectChange.RenameMetadataObject) change; + handleMetadataRenamed(rename.metadataObject(), rename.newMetadataObject()); + } else if (change != null) { + LOG.debug("Ignoring unsupported metadata object change: {}", change); + } + } + return Boolean.TRUE; + } + + @Override + public void close() throws IOException { + adminClient.close(Duration.ofMillis(properties.getRequestTimeoutMs())); + } + + private void applyRoleUpdateForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Role preUpdateRole, + Role updatedRole, + RoleChange[] changes, + Set<String> replacedRoleNames, + List<Role> replacementRoles) { + Map<String, SecurableObject> beforeObjects = new LinkedHashMap<>(); + Map<String, SecurableObject> afterObjects = new LinkedHashMap<>(); + if (preUpdateRole.securableObjects() != null) { + for (SecurableObject existing : preUpdateRole.securableObjects()) { + if (existing != null) { + String key = securableObjectKey(existing); + beforeObjects.put(key, existing); + afterObjects.put(key, existing); + } + } + } + + for (RoleChange change : changes) { + if (change instanceof RoleChange.AddSecurableObject) { + SecurableObject added = ((RoleChange.AddSecurableObject) change).getSecurableObject(); + if (added != null) { + afterObjects.put(securableObjectKey(added), added); + } + } else if (change instanceof RoleChange.RemoveSecurableObject) { + SecurableObject removed = ((RoleChange.RemoveSecurableObject) change).getSecurableObject(); + if (removed != null) { + String key = securableObjectKey(removed); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, removed); + } + afterObjects.remove(key); + } + } else if (change instanceof RoleChange.UpdateSecurableObject) { + RoleChange.UpdateSecurableObject update = (RoleChange.UpdateSecurableObject) change; + SecurableObject oldObj = update.getSecurableObject(); + SecurableObject newObj = update.getNewSecurableObject(); + if (oldObj != null) { + String key = securableObjectKey(oldObj); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, oldObj); + } + if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } else { + afterObjects.remove(key); + } + } else if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } + } + } + + Set<AclBinding> beforeBindings = new LinkedHashSet<>(); + for (SecurableObject beforeObj : beforeObjects.values()) { + beforeBindings.addAll(bindingsForSecurableObject(beforeObj, kafkaPrincipal)); + } + + Set<AclBinding> afterBindings = new LinkedHashSet<>(); + for (SecurableObject afterObj : afterObjects.values()) { + afterBindings.addAll(bindingsForSecurableObject(afterObj, kafkaPrincipal)); + } + + // Fallback delta if changes and preUpdateRole yielded identical before/after sets. + if (beforeBindings.equals(afterBindings)) { + beforeBindings.addAll(bindingsForRoles(List.of(preUpdateRole), kafkaPrincipal)); + afterBindings.addAll(bindingsForRoles(List.of(updatedRole), kafkaPrincipal)); + } + + Set<AclBinding> addedBindings = + new LinkedHashSet<>(Sets.difference(afterBindings, beforeBindings)); + Set<AclBinding> candidateRemovals = + new LinkedHashSet<>(Sets.difference(beforeBindings, afterBindings)); + + createAcls(addedBindings); + + removeBindingsPreservingActiveGrants( + principalType, + principalName, + candidateRemovals, + replacedRoleNames, + replacementRoles, + Collections.emptyMap(), + null); + } + + private void removeBindingsPreservingActiveGrants( + Owner.Type principalType, + String principalName, + Set<AclBinding> candidateRemovals, + Set<String> excludedRoleNames, + List<Role> extraActiveRoles, + Map<MetadataObject, Optional<Owner>> ownerOverrides, + @Nullable MetadataObject excludedObject) { + if (candidateRemovals == null || candidateRemovals.isEmpty()) { + return; + } + + String kafkaPrincipal = formatPrincipal(principalType, principalName); + Set<AclBinding> roleActiveBindings = + computeRoleBindingsForPrincipal( + principalType, + principalName, + kafkaPrincipal, + excludedRoleNames, + extraActiveRoles, + excludedObject); + Set<AclBinding> remaining = + new LinkedHashSet<>(Sets.difference(candidateRemovals, roleActiveBindings)); + if (remaining.isEmpty()) { + return; + } + + Set<AclBinding> ownerActiveBindings = + computeOwnerBindingsForPrincipal( + principalType, principalName, kafkaPrincipal, ownerOverrides, excludedObject); + Set<AclBinding> toDelete = Sets.difference(remaining, ownerActiveBindings); + deleteExactAcls(toDelete); Review Comment: Privilege updates to different roles can run concurrently: R1's revocation can read active grants, R2 can then create the same ACL, and R1 can delete it despite R2 remaining active. Serialize ACL creation and read/reconcile/delete operations per Kafka principal across grants, revocations, role updates, and ownership changes. Protecting only the final delete call does not prevent this race. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); + + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + applyRoleUpdateForPrincipal( + Owner.Type.USER, + username, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + applyRoleUpdateForPrincipal( + Owner.Type.GROUP, + groupName, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + user.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + group.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAdded(User user) throws RuntimeException { + // External SASL/OAuth IdP manages user existence; Kafka ACLs are added on role/owner grants. + return Boolean.TRUE; + } + + @Override + public Boolean onUserRemoved(User user) throws RuntimeException { + if (user == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatUserPrincipal(user.name())); Review Comment: The actual user and group removal paths in AccessControlManager/UserGroupManager delete stored entities without invoking these cleanup callbacks, leaving Kafka ACLs active for externally authenticated principals. Wire authorization notifications into single and bulk removal before deleting identities and their relations, and test removal through the public API. The same issue affects `onGroupRemoved` at line 298. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); + + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + applyRoleUpdateForPrincipal( + Owner.Type.USER, + username, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + applyRoleUpdateForPrincipal( + Owner.Type.GROUP, + groupName, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + user.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + group.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAdded(User user) throws RuntimeException { + // External SASL/OAuth IdP manages user existence; Kafka ACLs are added on role/owner grants. + return Boolean.TRUE; + } + + @Override + public Boolean onUserRemoved(User user) throws RuntimeException { + if (user == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatUserPrincipal(user.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAcquired(User user) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAdded(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupRemoved(Group group) throws RuntimeException { + if (group == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatGroupPrincipal(group.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAcquired(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onOwnerSet( + MetadataObject metadataObject, @Nullable Owner preOwner, @Nullable Owner newOwner) + throws RuntimeException { + if (metadataObject == null || !appliesToThisCatalog(metadataObject)) { + return Boolean.TRUE; + } + + if (preOwner != null && !sameOwner(preOwner, newOwner)) { + String prePrincipal = formatOwnerPrincipal(preOwner); + Set<AclBinding> candidateRemovals = + KafkaPrivilegeMapper.ownerAclBindings(metadataObject, prePrincipal, properties); + Map<MetadataObject, Optional<Owner>> ownerOverrides = new HashMap<>(); + ownerOverrides.put(metadataObject, Optional.ofNullable(newOwner)); + removeBindingsPreservingActiveGrants( + preOwner.type(), + preOwner.name(), + candidateRemovals, + Collections.emptySet(), + Collections.emptyList(), + ownerOverrides, + null); + } + + if (newOwner != null) { + String newPrincipal = formatOwnerPrincipal(newOwner); + createAcls(KafkaPrivilegeMapper.ownerAclBindings(metadataObject, newPrincipal, properties)); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onMetadataUpdated(MetadataObjectChange... changes) throws RuntimeException { + if (changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + for (MetadataObjectChange change : changes) { + if (change instanceof MetadataObjectChange.RemoveMetadataObject) { + MetadataObject removed = + ((MetadataObjectChange.RemoveMetadataObject) change).metadataObject(); + handleMetadataRemoved(removed); + } else if (change instanceof MetadataObjectChange.RenameMetadataObject) { + MetadataObjectChange.RenameMetadataObject rename = + (MetadataObjectChange.RenameMetadataObject) change; + handleMetadataRenamed(rename.metadataObject(), rename.newMetadataObject()); + } else if (change != null) { + LOG.debug("Ignoring unsupported metadata object change: {}", change); + } + } + return Boolean.TRUE; + } + + @Override + public void close() throws IOException { + adminClient.close(Duration.ofMillis(properties.getRequestTimeoutMs())); + } + + private void applyRoleUpdateForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Role preUpdateRole, + Role updatedRole, + RoleChange[] changes, + Set<String> replacedRoleNames, + List<Role> replacementRoles) { + Map<String, SecurableObject> beforeObjects = new LinkedHashMap<>(); + Map<String, SecurableObject> afterObjects = new LinkedHashMap<>(); + if (preUpdateRole.securableObjects() != null) { + for (SecurableObject existing : preUpdateRole.securableObjects()) { + if (existing != null) { + String key = securableObjectKey(existing); + beforeObjects.put(key, existing); + afterObjects.put(key, existing); + } + } + } + + for (RoleChange change : changes) { + if (change instanceof RoleChange.AddSecurableObject) { + SecurableObject added = ((RoleChange.AddSecurableObject) change).getSecurableObject(); + if (added != null) { + afterObjects.put(securableObjectKey(added), added); + } + } else if (change instanceof RoleChange.RemoveSecurableObject) { + SecurableObject removed = ((RoleChange.RemoveSecurableObject) change).getSecurableObject(); + if (removed != null) { + String key = securableObjectKey(removed); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, removed); + } + afterObjects.remove(key); + } + } else if (change instanceof RoleChange.UpdateSecurableObject) { + RoleChange.UpdateSecurableObject update = (RoleChange.UpdateSecurableObject) change; + SecurableObject oldObj = update.getSecurableObject(); + SecurableObject newObj = update.getNewSecurableObject(); + if (oldObj != null) { + String key = securableObjectKey(oldObj); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, oldObj); + } + if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } else { + afterObjects.remove(key); + } + } else if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } + } + } + + Set<AclBinding> beforeBindings = new LinkedHashSet<>(); + for (SecurableObject beforeObj : beforeObjects.values()) { + beforeBindings.addAll(bindingsForSecurableObject(beforeObj, kafkaPrincipal)); + } + + Set<AclBinding> afterBindings = new LinkedHashSet<>(); + for (SecurableObject afterObj : afterObjects.values()) { + afterBindings.addAll(bindingsForSecurableObject(afterObj, kafkaPrincipal)); + } + + // Fallback delta if changes and preUpdateRole yielded identical before/after sets. + if (beforeBindings.equals(afterBindings)) { + beforeBindings.addAll(bindingsForRoles(List.of(preUpdateRole), kafkaPrincipal)); + afterBindings.addAll(bindingsForRoles(List.of(updatedRole), kafkaPrincipal)); + } + + Set<AclBinding> addedBindings = + new LinkedHashSet<>(Sets.difference(afterBindings, beforeBindings)); + Set<AclBinding> candidateRemovals = + new LinkedHashSet<>(Sets.difference(beforeBindings, afterBindings)); + + createAcls(addedBindings); + + removeBindingsPreservingActiveGrants( + principalType, + principalName, + candidateRemovals, + replacedRoleNames, + replacementRoles, + Collections.emptyMap(), + null); + } + + private void removeBindingsPreservingActiveGrants( + Owner.Type principalType, + String principalName, + Set<AclBinding> candidateRemovals, + Set<String> excludedRoleNames, + List<Role> extraActiveRoles, + Map<MetadataObject, Optional<Owner>> ownerOverrides, + @Nullable MetadataObject excludedObject) { + if (candidateRemovals == null || candidateRemovals.isEmpty()) { + return; + } + + String kafkaPrincipal = formatPrincipal(principalType, principalName); + Set<AclBinding> roleActiveBindings = + computeRoleBindingsForPrincipal( + principalType, + principalName, + kafkaPrincipal, + excludedRoleNames, + extraActiveRoles, + excludedObject); + Set<AclBinding> remaining = + new LinkedHashSet<>(Sets.difference(candidateRemovals, roleActiveBindings)); + if (remaining.isEmpty()) { + return; + } + + Set<AclBinding> ownerActiveBindings = + computeOwnerBindingsForPrincipal( + principalType, principalName, kafkaPrincipal, ownerOverrides, excludedObject); + Set<AclBinding> toDelete = Sets.difference(remaining, ownerActiveBindings); + deleteExactAcls(toDelete); Review Comment: When user-principal-type and group-principal-type are equal, revoking a role from user `shared` can delete ACLs still required by group `shared`, because reconciliation checks only one identity. Union both identities' active role and ownership bindings before deletion, as the topic-drop path does. Apply this to role revocations, updates/deletions, and ownership transfers, distinguishing identity-specific revocations from changes to a role held by both identities. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationProperties.java: ########## @@ -0,0 +1,378 @@ +/* + * 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.kafka; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.authorization.common.AuthorizationProperties; +import org.apache.gravitino.connector.BaseCatalog; +import org.apache.gravitino.connector.authorization.BaseAuthorization; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.common.resource.PatternType; + +/** + * Configuration properties parser and validator for {@link KafkaAuthorizationPlugin}. + * + * <p>Consumes catalog-level Kafka settings ({@code bootstrap.servers} and {@code + * gravitino.bypass.*}) alongside plugin-specific {@code authorization.kafka.*} settings. + */ +public class KafkaAuthorizationProperties extends AuthorizationProperties { + + /** Property prefix for Kafka authorization settings. */ + public static final String PREFIX = "authorization.kafka."; + + /** Property prefix whose suffix is forwarded directly to Kafka {@code AdminClient}. */ + public static final String ADMIN_CLIENT_PREFIX = PREFIX + "admin."; + + /** Catalog property specifying Kafka bootstrap servers. */ + public static final String BOOTSTRAP_SERVERS = "bootstrap.servers"; + + /** Optional plugin override specifying Kafka bootstrap servers. */ + public static final String AUTHZ_BOOTSTRAP_SERVERS = PREFIX + "bootstrap.servers"; + + /** Principal type prefix used for Gravitino users in Kafka ACL entries (default {@code User}). */ + public static final String USER_PRINCIPAL_TYPE = PREFIX + "user-principal-type"; + + /** + * Principal type prefix used for Gravitino groups in Kafka ACL entries (default {@code Group}). + */ + public static final String GROUP_PRINCIPAL_TYPE = PREFIX + "group-principal-type"; + + /** Resource name pattern for Kafka consumer group ACLs granted on {@code CONSUME_TOPIC}. */ + public static final String CONSUMER_GROUP_PATTERN = PREFIX + "consumer-group-pattern"; + + /** Pattern type ({@code LITERAL} or {@code PREFIXED}) for {@link #CONSUMER_GROUP_PATTERN}. */ + public static final String CONSUMER_GROUP_PATTERN_TYPE = PREFIX + "consumer-group-pattern-type"; + + /** Host filter written to Kafka ACL entries (default {@code *}). */ + public static final String ACL_HOST = PREFIX + "host"; + + /** Whether {@code ALLOW PRODUCE_TOPIC} also grants {@code CLUSTER:IDEMPOTENT_WRITE}. */ + public static final String IDEMPOTENT_WRITE_ACL_ENABLED = PREFIX + "idempotent-write-acl.enabled"; + + /** Timeout in milliseconds for Kafka {@code AdminClient} ACL requests (default {@code 30000}). */ + public static final String REQUEST_TIMEOUT_MS = PREFIX + "request-timeout-ms"; + + /** Default Kafka user principal type prefix. */ + public static final String DEFAULT_USER_PRINCIPAL_TYPE = "User"; + + /** Default Kafka group principal type prefix. */ + public static final String DEFAULT_GROUP_PRINCIPAL_TYPE = "Group"; + + /** Default consumer group resource pattern. */ + public static final String DEFAULT_CONSUMER_GROUP_PATTERN = "*"; + + /** Default consumer group resource pattern type. */ + public static final String DEFAULT_CONSUMER_GROUP_PATTERN_TYPE = PatternType.LITERAL.name(); + + /** Default ACL host value. */ + public static final String DEFAULT_ACL_HOST = "*"; + + /** Default flag for granting cluster idempotent write on produce grants. */ + public static final boolean DEFAULT_IDEMPOTENT_WRITE_ACL_ENABLED = true; + + /** Default Kafka AdminClient request timeout in milliseconds. */ + public static final int DEFAULT_REQUEST_TIMEOUT_MS = 30000; + + private final Map<String, String> rawConfig; + + /** + * Constructs {@link KafkaAuthorizationProperties} from raw catalog and authorization config. + * + * @param properties Configuration map passed to {@link KafkaAuthorization#newPlugin}. + */ + public KafkaAuthorizationProperties(Map<String, String> properties) { + super(properties == null ? Collections.emptyMap() : properties); + ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); + if (properties != null) { + properties.forEach( + (k, v) -> { + if (k != null && v != null) { + builder.put(k, v); + } + }); + } + this.rawConfig = builder.build(); + } + + @Override + public String getPropertiesPrefix() { + return PREFIX; + } + + @Override + public void validate() { + String bootstrapServers = getBootstrapServers(); + if (StringUtils.isBlank(bootstrapServers)) { + throw new IllegalArgumentException( + String.format( + "Missing required Kafka bootstrap servers configuration (%s or %s)", + BOOTSTRAP_SERVERS, AUTHZ_BOOTSTRAP_SERVERS)); + } + + if (StringUtils.isBlank(getUserPrincipalType())) { + throw new IllegalArgumentException(USER_PRINCIPAL_TYPE + " must not be blank"); + } + if (StringUtils.isBlank(getGroupPrincipalType())) { + throw new IllegalArgumentException(GROUP_PRINCIPAL_TYPE + " must not be blank"); + } + if (StringUtils.isBlank(getConsumerGroupPattern())) { + throw new IllegalArgumentException(CONSUMER_GROUP_PATTERN + " must not be blank"); + } + if (StringUtils.isBlank(getAclHost())) { + throw new IllegalArgumentException(ACL_HOST + " must not be blank"); + } + + // Validate consumer group pattern type + getConsumerGroupPatternType(); + + // Validate boolean flag strictly + String idempotentRaw = properties.get(IDEMPOTENT_WRITE_ACL_ENABLED); + if (idempotentRaw != null + && !"true".equalsIgnoreCase(idempotentRaw.trim()) + && !"false".equalsIgnoreCase(idempotentRaw.trim())) { + throw new IllegalArgumentException( + String.format( + "Invalid boolean value '%s' for %s; expected 'true' or 'false'", + idempotentRaw, IDEMPOTENT_WRITE_ACL_ENABLED)); + } + + // Validate request timeout + int timeoutMs = getRequestTimeoutMs(); + if (timeoutMs <= 0) { + throw new IllegalArgumentException(REQUEST_TIMEOUT_MS + " must be greater than 0"); + } + + // Validate catalog ID if provided + getCatalogId(); + } + + /** + * Returns the resolved Kafka bootstrap servers string. + * + * @return The Kafka bootstrap servers. + */ + public String getBootstrapServers() { + String override = properties.get(AUTHZ_BOOTSTRAP_SERVERS); + if (StringUtils.isNotBlank(override)) { + return override.trim(); + } + String catalogBootstrap = rawConfig.get(BOOTSTRAP_SERVERS); + return catalogBootstrap == null ? null : catalogBootstrap.trim(); + } + + /** + * Returns the Kafka principal type prefix used for Gravitino users. + * + * @return Principal type string (e.g. {@code User}). + */ + public String getUserPrincipalType() { + return properties.getOrDefault(USER_PRINCIPAL_TYPE, DEFAULT_USER_PRINCIPAL_TYPE).trim(); + } + + /** + * Returns the Kafka principal type prefix used for Gravitino groups. + * + * @return Principal type string (e.g. {@code Group}). + */ + public String getGroupPrincipalType() { + return properties.getOrDefault(GROUP_PRINCIPAL_TYPE, DEFAULT_GROUP_PRINCIPAL_TYPE).trim(); + } + + /** + * Returns the Kafka consumer group resource name pattern granted on {@code CONSUME_TOPIC}. + * + * @return Consumer group pattern string. + */ + public String getConsumerGroupPattern() { + return properties.getOrDefault(CONSUMER_GROUP_PATTERN, DEFAULT_CONSUMER_GROUP_PATTERN).trim(); + } + + /** + * Returns the Kafka {@link PatternType} for consumer group ACLs. + * + * @return {@link PatternType#LITERAL} or {@link PatternType#PREFIXED}. + */ + public PatternType getConsumerGroupPatternType() { + String raw = + properties + .getOrDefault(CONSUMER_GROUP_PATTERN_TYPE, DEFAULT_CONSUMER_GROUP_PATTERN_TYPE) + .trim() + .toUpperCase(Locale.ROOT); + if (PatternType.LITERAL.name().equals(raw)) { + return PatternType.LITERAL; + } + if (PatternType.PREFIXED.name().equals(raw)) { + return PatternType.PREFIXED; + } + throw new IllegalArgumentException( + String.format( + "Unsupported %s '%s'; expected LITERAL or PREFIXED", CONSUMER_GROUP_PATTERN_TYPE, raw)); + } + + /** + * Returns the host value applied to created Kafka ACL entries. + * + * @return ACL host string (default {@code *}). + */ + public String getAclHost() { + return properties.getOrDefault(ACL_HOST, DEFAULT_ACL_HOST).trim(); + } + + /** + * Returns whether {@code ALLOW PRODUCE_TOPIC} includes {@code CLUSTER:IDEMPOTENT_WRITE}. + * + * @return {@code true} if idempotent write ACLs should be emitted. + */ + public boolean isIdempotentWriteAclEnabled() { + String raw = properties.get(IDEMPOTENT_WRITE_ACL_ENABLED); + if (raw == null) { + return DEFAULT_IDEMPOTENT_WRITE_ACL_ENABLED; + } + String trimmed = raw.trim(); + if ("true".equalsIgnoreCase(trimmed)) { + return true; + } + if ("false".equalsIgnoreCase(trimmed)) { + return false; + } + throw new IllegalArgumentException( + String.format( + "Invalid boolean value '%s' for %s; expected 'true' or 'false'", + raw, IDEMPOTENT_WRITE_ACL_ENABLED)); + } + + /** + * Returns the Kafka {@code AdminClient} request timeout in milliseconds. + * + * @return Positive request timeout in milliseconds. + */ + public int getRequestTimeoutMs() { + String raw = properties.get(REQUEST_TIMEOUT_MS); + if (raw == null) { + return DEFAULT_REQUEST_TIMEOUT_MS; + } + try { + int parsed = Integer.parseInt(raw.trim()); + if (parsed <= 0) { + throw new IllegalArgumentException(REQUEST_TIMEOUT_MS + " must be greater than 0"); + } + return parsed; + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + String.format("Invalid integer value '%s' for %s", raw, REQUEST_TIMEOUT_MS), e); + } + } + + /** + * Returns the Gravitino catalog entity ID injected by {@code BaseAuthorization}, if present. + * + * @return The catalog ID, or {@code null} if absent. + */ + public Long getCatalogId() { + String rawId = rawConfig.get(BaseAuthorization.CATALOG_ID); + if (StringUtils.isBlank(rawId)) { + return null; + } + try { + return Long.parseLong(rawId.trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + String.format("Invalid catalog ID '%s' in %s", rawId, BaseAuthorization.CATALOG_ID), e); + } + } + + /** + * Formats a Gravitino user name into a Kafka ACL principal string. + * + * @param username Gravitino user name. + * @return Formatted Kafka principal (e.g. {@code User:alice}). + */ + public String formatUserPrincipal(String username) { + Preconditions.checkArgument(StringUtils.isNotBlank(username), "Username must not be blank"); + return getUserPrincipalType() + ":" + username; + } + + /** + * Formats a Gravitino group name into a Kafka ACL principal string. + * + * @param groupName Gravitino group name. + * @return Formatted Kafka principal (e.g. {@code Group:analytics}). + */ + public String formatGroupPrincipal(String groupName) { + Preconditions.checkArgument(StringUtils.isNotBlank(groupName), "Group name must not be blank"); + return getGroupPrincipalType() + ":" + groupName; Review Comment: The user and group APIs accept `*`, which becomes Kafka's reserved `User:*` principal with the default user prefix or a group prefix configured as `User`. Grants, denials, and ownership for that single Gravitino identity then affect every Kafka user. Reject `User:*` in both formatters, including `formatGroupPrincipal` at lines 324–325. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); + + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + applyRoleUpdateForPrincipal( + Owner.Type.USER, + username, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + applyRoleUpdateForPrincipal( + Owner.Type.GROUP, + groupName, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + user.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + createAcls(bindingsForRoles(roles, principal)); Review Comment: StandardAuthorizer does not expand group membership: a member authenticated as `User:alice` never matches the emitted `Group:eng` ACL. Group ALLOW grants and ownership therefore do not authorize members, while group DENY grants fail to restrict members with user-level ALLOW grants. Materialize permissions onto member principals with membership reconciliation, or reject unsupported GROUP operations and document the required group-aware broker integration. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaPrivilegeMapper.java: ########## @@ -0,0 +1,284 @@ +/* + * 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.kafka; + +import com.google.common.base.Preconditions; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Privilege; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Translates Apache Gravitino {@link MetadataObject} privileges and ownership into native Apache + * Kafka {@link AclBinding} entries. + */ +public final class KafkaPrivilegeMapper { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaPrivilegeMapper.class); + + private static final ResourcePattern WILDCARD_TOPIC_RESOURCE = + new ResourcePattern(ResourceType.TOPIC, "*", PatternType.LITERAL); + + private static final ResourcePattern CLUSTER_RESOURCE = + new ResourcePattern(ResourceType.CLUSTER, Resource.CLUSTER_NAME, PatternType.LITERAL); + + private static final Set<AclOperation> OWNER_TOPIC_OPERATIONS; + + static { + Set<AclOperation> ops = new LinkedHashSet<>(); + ops.add(AclOperation.READ); + ops.add(AclOperation.WRITE); + ops.add(AclOperation.CREATE); + ops.add(AclOperation.DELETE); + ops.add(AclOperation.ALTER); + ops.add(AclOperation.DESCRIBE); + ops.add(AclOperation.ALTER_CONFIGS); + ops.add(AclOperation.DESCRIBE_CONFIGS); + OWNER_TOPIC_OPERATIONS = Collections.unmodifiableSet(ops); + } + + private KafkaPrivilegeMapper() {} + + /** + * Maps a Gravitino privilege on a metadata object for a specific Kafka principal into one or more + * Kafka {@link AclBinding}s. + * + * @param metadataObject Target securable object. + * @param privilege Gravitino privilege (name + ALLOW/DENY condition). + * @param kafkaPrincipal Formatted Kafka principal (e.g. {@code User:alice}). + * @param properties Authorization plugin configuration properties. + * @return Immutable or ordered set of Kafka ACL bindings (empty if non-Kafka privilege or type). + */ + public static Set<AclBinding> toAclBindings( + MetadataObject metadataObject, + Privilege privilege, + String kafkaPrincipal, + KafkaAuthorizationProperties properties) { + Preconditions.checkArgument(metadataObject != null, "MetadataObject must not be null"); + Preconditions.checkArgument(privilege != null, "Privilege must not be null"); + Preconditions.checkArgument(kafkaPrincipal != null, "Kafka principal must not be null"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + + ResourcePattern topicTarget = resolveTopicResource(metadataObject); + if (topicTarget == null) { + return Collections.emptySet(); + } + + AclPermissionType permissionType = toPermissionType(privilege.condition()); + String host = properties.getAclHost(); + Set<AclBinding> bindings = new LinkedHashSet<>(); + + switch (privilege.name()) { + case PRODUCE_TOPIC: + if (permissionType == AclPermissionType.ALLOW) { + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.WRITE, AclPermissionType.ALLOW))); + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.DESCRIBE, AclPermissionType.ALLOW))); + if (properties.isIdempotentWriteAclEnabled()) { + bindings.add( + new AclBinding( + CLUSTER_RESOURCE, + new AccessControlEntry( + kafkaPrincipal, + host, + AclOperation.IDEMPOTENT_WRITE, + AclPermissionType.ALLOW))); + } + } else { + // Only deny the primary WRITE operation so shared DESCRIBE or cluster ops remain usable. + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.WRITE, AclPermissionType.DENY))); + } + break; + + case CONSUME_TOPIC: + if (permissionType == AclPermissionType.ALLOW) { + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.READ, AclPermissionType.ALLOW))); + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.DESCRIBE, AclPermissionType.ALLOW))); + bindings.add( + new AclBinding( + consumerGroupResource(properties), + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.READ, AclPermissionType.ALLOW))); + } else { + // Only deny topic READ so consuming other topics or producing is unaffected. + bindings.add( + new AclBinding( + topicTarget, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.READ, AclPermissionType.DENY))); + } + break; + + case CREATE_TOPIC: + if (permissionType == AclPermissionType.ALLOW) { + bindings.add( + new AclBinding( + CLUSTER_RESOURCE, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.CREATE, AclPermissionType.ALLOW))); Review Comment: Kafka authorizes CreateTopics through CLUSTER:CREATE before checking topic permissions, so an ALLOW CREATE_TOPIC grant can bypass another role's topic-level DENY. Remove the cluster CREATE grant from both this mapping and the ownership mapping at lines 237–243; their TOPIC CREATE bindings already permit scoped creation. Update the documented mapping and add real-broker tests combining CREATE denials with role grants and parent ownership. ########## authorizations/authorization-kafka/src/main/java/org/apache/gravitino/authorization/kafka/KafkaAuthorizationPlugin.java: ########## @@ -0,0 +1,1010 @@ +/* + * 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.kafka; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import javax.annotation.Nullable; +import org.apache.commons.lang3.StringUtils; +import org.apache.gravitino.Audit; +import org.apache.gravitino.MetadataObject; +import org.apache.gravitino.authorization.Group; +import org.apache.gravitino.authorization.MetadataObjectChange; +import org.apache.gravitino.authorization.Owner; +import org.apache.gravitino.authorization.Privilege; +import org.apache.gravitino.authorization.Role; +import org.apache.gravitino.authorization.RoleChange; +import org.apache.gravitino.authorization.SecurableObject; +import org.apache.gravitino.authorization.User; +import org.apache.gravitino.connector.authorization.AuthorizationPlugin; +import org.apache.gravitino.exceptions.AuthorizationPluginException; +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.common.acl.AccessControlEntry; +import org.apache.kafka.common.acl.AccessControlEntryFilter; +import org.apache.kafka.common.acl.AclBinding; +import org.apache.kafka.common.acl.AclBindingFilter; +import org.apache.kafka.common.acl.AclOperation; +import org.apache.kafka.common.acl.AclPermissionType; +import org.apache.kafka.common.resource.PatternType; +import org.apache.kafka.common.resource.Resource; +import org.apache.kafka.common.resource.ResourcePattern; +import org.apache.kafka.common.resource.ResourcePatternFilter; +import org.apache.kafka.common.resource.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link AuthorizationPlugin} implementation that pushes Apache Gravitino RBAC grants, revocations, + * ownership changes, and topic metadata updates to Kafka brokers using {@link AdminClient}. + */ +public class KafkaAuthorizationPlugin implements AuthorizationPlugin { + + private static final Logger LOG = LoggerFactory.getLogger(KafkaAuthorizationPlugin.class); + + private final KafkaAuthorizationProperties properties; + private final AdminClient adminClient; + private final KafkaAuthorizationStateProvider stateProvider; + + private volatile String metalake; + private volatile String catalogName; + + /** + * Creates a {@link KafkaAuthorizationPlugin} backed by a new Kafka {@link AdminClient} and the + * default {@link EntityStoreAuthorizationStateProvider}. + * + * @param metalake Metalake name associated with this catalog plugin. + * @param properties Validated Kafka authorization configuration properties. + */ + public KafkaAuthorizationPlugin(String metalake, KafkaAuthorizationProperties properties) { + this( + metalake, + properties, + AdminClient.create(properties.toAdminClientProperties()), + new EntityStoreAuthorizationStateProvider(), + null); + } + + @VisibleForTesting + KafkaAuthorizationPlugin( + String metalake, + KafkaAuthorizationProperties properties, + AdminClient adminClient, + KafkaAuthorizationStateProvider stateProvider, + @Nullable String initialCatalogName) { + Preconditions.checkArgument( + StringUtils.isNotBlank(metalake), "Metalake name must not be blank"); + Preconditions.checkArgument(properties != null, "Properties must not be null"); + Preconditions.checkArgument(adminClient != null, "AdminClient must not be null"); + Preconditions.checkArgument(stateProvider != null, "StateProvider must not be null"); + this.metalake = metalake; + this.properties = properties; + this.adminClient = adminClient; + this.stateProvider = stateProvider; + this.catalogName = initialCatalogName; + } + + @Override + public Boolean onRoleCreated(Role role) throws RuntimeException { + // Roles carry no Kafka user/group principals until granted to a user or group. + return Boolean.TRUE; + } + + @Override + public Boolean onRoleAcquired(Role role) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onRoleDeleted(Role role) throws RuntimeException { + if (role == null) { + return Boolean.TRUE; + } + + Set<String> excludedRoles = Collections.singleton(role.name()); + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + username, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + Set<AclBinding> candidateRemovals = bindingsForRoles(List.of(role), principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + groupName, + candidateRemovals, + excludedRoles, + Collections.emptyList(), + Collections.emptyMap(), + null); + } + return Boolean.TRUE; + } + + @Override + public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException { + if (role == null || changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + List<String> boundUsers = stateProvider.listUserNamesByRole(metalake, role.name()); + List<String> boundGroups = stateProvider.listGroupNamesByRole(metalake, role.name()); + if (boundUsers.isEmpty() && boundGroups.isEmpty()) { + return Boolean.TRUE; + } + + Role updatedRole = applyRoleChanges(role, changes); + Set<String> replacedRoleNames = Collections.singleton(role.name()); + List<Role> replacementRoles = Collections.singletonList(updatedRole); + + for (String username : boundUsers) { + String principal = properties.formatUserPrincipal(username); + applyRoleUpdateForPrincipal( + Owner.Type.USER, + username, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + for (String groupName : boundGroups) { + String principal = properties.formatGroupPrincipal(groupName); + applyRoleUpdateForPrincipal( + Owner.Type.GROUP, + groupName, + principal, + role, + updatedRole, + changes, + replacedRoleNames, + replacementRoles); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException { + if (user == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatUserPrincipal(user.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.USER, + user.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + createAcls(bindingsForRoles(roles, principal)); + return Boolean.TRUE; + } + + @Override + public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException { + if (group == null || roles == null || roles.isEmpty()) { + return Boolean.TRUE; + } + String principal = properties.formatGroupPrincipal(group.name()); + Set<AclBinding> candidateRemovals = bindingsForRoles(roles, principal); + removeBindingsPreservingActiveGrants( + Owner.Type.GROUP, + group.name(), + candidateRemovals, + extractRoleNames(roles), + Collections.emptyList(), + Collections.emptyMap(), + null); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAdded(User user) throws RuntimeException { + // External SASL/OAuth IdP manages user existence; Kafka ACLs are added on role/owner grants. + return Boolean.TRUE; + } + + @Override + public Boolean onUserRemoved(User user) throws RuntimeException { + if (user == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatUserPrincipal(user.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onUserAcquired(User user) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAdded(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onGroupRemoved(Group group) throws RuntimeException { + if (group == null) { + return Boolean.TRUE; + } + deleteAclsByPrincipal(properties.formatGroupPrincipal(group.name())); + return Boolean.TRUE; + } + + @Override + public Boolean onGroupAcquired(Group group) throws RuntimeException { + return Boolean.TRUE; + } + + @Override + public Boolean onOwnerSet( + MetadataObject metadataObject, @Nullable Owner preOwner, @Nullable Owner newOwner) + throws RuntimeException { + if (metadataObject == null || !appliesToThisCatalog(metadataObject)) { + return Boolean.TRUE; + } + + if (preOwner != null && !sameOwner(preOwner, newOwner)) { + String prePrincipal = formatOwnerPrincipal(preOwner); + Set<AclBinding> candidateRemovals = + KafkaPrivilegeMapper.ownerAclBindings(metadataObject, prePrincipal, properties); + Map<MetadataObject, Optional<Owner>> ownerOverrides = new HashMap<>(); + ownerOverrides.put(metadataObject, Optional.ofNullable(newOwner)); + removeBindingsPreservingActiveGrants( + preOwner.type(), + preOwner.name(), + candidateRemovals, + Collections.emptySet(), + Collections.emptyList(), + ownerOverrides, + null); + } + + if (newOwner != null) { + String newPrincipal = formatOwnerPrincipal(newOwner); + createAcls(KafkaPrivilegeMapper.ownerAclBindings(metadataObject, newPrincipal, properties)); + } + + return Boolean.TRUE; + } + + @Override + public Boolean onMetadataUpdated(MetadataObjectChange... changes) throws RuntimeException { + if (changes == null || changes.length == 0) { + return Boolean.TRUE; + } + + for (MetadataObjectChange change : changes) { + if (change instanceof MetadataObjectChange.RemoveMetadataObject) { + MetadataObject removed = + ((MetadataObjectChange.RemoveMetadataObject) change).metadataObject(); + handleMetadataRemoved(removed); + } else if (change instanceof MetadataObjectChange.RenameMetadataObject) { + MetadataObjectChange.RenameMetadataObject rename = + (MetadataObjectChange.RenameMetadataObject) change; + handleMetadataRenamed(rename.metadataObject(), rename.newMetadataObject()); + } else if (change != null) { + LOG.debug("Ignoring unsupported metadata object change: {}", change); + } + } + return Boolean.TRUE; + } + + @Override + public void close() throws IOException { + adminClient.close(Duration.ofMillis(properties.getRequestTimeoutMs())); + } + + private void applyRoleUpdateForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Role preUpdateRole, + Role updatedRole, + RoleChange[] changes, + Set<String> replacedRoleNames, + List<Role> replacementRoles) { + Map<String, SecurableObject> beforeObjects = new LinkedHashMap<>(); + Map<String, SecurableObject> afterObjects = new LinkedHashMap<>(); + if (preUpdateRole.securableObjects() != null) { + for (SecurableObject existing : preUpdateRole.securableObjects()) { + if (existing != null) { + String key = securableObjectKey(existing); + beforeObjects.put(key, existing); + afterObjects.put(key, existing); + } + } + } + + for (RoleChange change : changes) { + if (change instanceof RoleChange.AddSecurableObject) { + SecurableObject added = ((RoleChange.AddSecurableObject) change).getSecurableObject(); + if (added != null) { + afterObjects.put(securableObjectKey(added), added); + } + } else if (change instanceof RoleChange.RemoveSecurableObject) { + SecurableObject removed = ((RoleChange.RemoveSecurableObject) change).getSecurableObject(); + if (removed != null) { + String key = securableObjectKey(removed); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, removed); + } + afterObjects.remove(key); + } + } else if (change instanceof RoleChange.UpdateSecurableObject) { + RoleChange.UpdateSecurableObject update = (RoleChange.UpdateSecurableObject) change; + SecurableObject oldObj = update.getSecurableObject(); + SecurableObject newObj = update.getNewSecurableObject(); + if (oldObj != null) { + String key = securableObjectKey(oldObj); + if (!beforeObjects.containsKey(key) && !afterObjects.containsKey(key)) { + beforeObjects.put(key, oldObj); + } + if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } else { + afterObjects.remove(key); + } + } else if (newObj != null) { + afterObjects.put(securableObjectKey(newObj), newObj); + } + } + } + + Set<AclBinding> beforeBindings = new LinkedHashSet<>(); + for (SecurableObject beforeObj : beforeObjects.values()) { + beforeBindings.addAll(bindingsForSecurableObject(beforeObj, kafkaPrincipal)); + } + + Set<AclBinding> afterBindings = new LinkedHashSet<>(); + for (SecurableObject afterObj : afterObjects.values()) { + afterBindings.addAll(bindingsForSecurableObject(afterObj, kafkaPrincipal)); + } + + // Fallback delta if changes and preUpdateRole yielded identical before/after sets. + if (beforeBindings.equals(afterBindings)) { + beforeBindings.addAll(bindingsForRoles(List.of(preUpdateRole), kafkaPrincipal)); + afterBindings.addAll(bindingsForRoles(List.of(updatedRole), kafkaPrincipal)); + } + + Set<AclBinding> addedBindings = + new LinkedHashSet<>(Sets.difference(afterBindings, beforeBindings)); + Set<AclBinding> candidateRemovals = + new LinkedHashSet<>(Sets.difference(beforeBindings, afterBindings)); + + createAcls(addedBindings); + + removeBindingsPreservingActiveGrants( + principalType, + principalName, + candidateRemovals, + replacedRoleNames, + replacementRoles, + Collections.emptyMap(), + null); + } + + private void removeBindingsPreservingActiveGrants( + Owner.Type principalType, + String principalName, + Set<AclBinding> candidateRemovals, + Set<String> excludedRoleNames, + List<Role> extraActiveRoles, + Map<MetadataObject, Optional<Owner>> ownerOverrides, + @Nullable MetadataObject excludedObject) { + if (candidateRemovals == null || candidateRemovals.isEmpty()) { + return; + } + + String kafkaPrincipal = formatPrincipal(principalType, principalName); + Set<AclBinding> roleActiveBindings = + computeRoleBindingsForPrincipal( + principalType, + principalName, + kafkaPrincipal, + excludedRoleNames, + extraActiveRoles, + excludedObject); + Set<AclBinding> remaining = + new LinkedHashSet<>(Sets.difference(candidateRemovals, roleActiveBindings)); + if (remaining.isEmpty()) { + return; + } + + Set<AclBinding> ownerActiveBindings = + computeOwnerBindingsForPrincipal( + principalType, principalName, kafkaPrincipal, ownerOverrides, excludedObject); + Set<AclBinding> toDelete = Sets.difference(remaining, ownerActiveBindings); + deleteExactAcls(toDelete); + } + + private Set<AclBinding> collectActiveAclBindingsForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Set<String> excludedRoleNames, + List<Role> extraActiveRoles, + Map<MetadataObject, Optional<Owner>> ownerOverrides, + @Nullable MetadataObject excludedObject) { + Set<AclBinding> activeBindings = + computeRoleBindingsForPrincipal( + principalType, + principalName, + kafkaPrincipal, + excludedRoleNames, + extraActiveRoles, + excludedObject); + activeBindings.addAll( + computeOwnerBindingsForPrincipal( + principalType, principalName, kafkaPrincipal, ownerOverrides, excludedObject)); + return activeBindings; + } + + private Set<AclBinding> computeRoleBindingsForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Set<String> excludedRoleNames, + List<Role> extraActiveRoles, + @Nullable MetadataObject excludedObject) { + Set<AclBinding> active = new LinkedHashSet<>(); + + List<Role> storedRoles = + principalType == Owner.Type.USER + ? stateProvider.listRolesForUser(metalake, principalName) + : stateProvider.listRolesForGroup(metalake, principalName); + for (Role role : storedRoles) { + if (role != null && !excludedRoleNames.contains(role.name())) { + active.addAll( + bindingsForRolesExcludingObject( + Collections.singletonList(role), kafkaPrincipal, excludedObject)); + } + } + if (extraActiveRoles != null && !extraActiveRoles.isEmpty()) { + active.addAll( + bindingsForRolesExcludingObject(extraActiveRoles, kafkaPrincipal, excludedObject)); + } + return active; + } + + private Set<AclBinding> computeOwnerBindingsForPrincipal( + Owner.Type principalType, + String principalName, + String kafkaPrincipal, + Map<MetadataObject, Optional<Owner>> ownerOverrides, + @Nullable MetadataObject excludedObject) { + Set<AclBinding> active = new LinkedHashSet<>(); + String resolvedCatalog = resolveCatalogName(); + List<MetadataObject> ownedObjects = + stateProvider.listOwnedObjectsForPrincipal( + metalake, resolvedCatalog, principalType, principalName); + for (MetadataObject owned : ownedObjects) { + if (owned == null || !appliesToThisCatalog(owned)) { + continue; + } + if (excludedObject != null && sameMetadataObject(owned, excludedObject)) { + continue; + } + Optional<Optional<Owner>> override = findOwnerOverride(ownerOverrides, owned); + if (override.isPresent()) { + Optional<Owner> effectiveOwner = override.get(); + if (effectiveOwner.isEmpty() + || effectiveOwner.get().type() != principalType + || !principalName.equals(effectiveOwner.get().name())) { + continue; + } + } + active.addAll(KafkaPrivilegeMapper.ownerAclBindings(owned, kafkaPrincipal, properties)); + } + + for (Map.Entry<MetadataObject, Optional<Owner>> entry : ownerOverrides.entrySet()) { + MetadataObject overriddenObject = entry.getKey(); + Optional<Owner> effectiveOwner = entry.getValue(); + if (overriddenObject != null + && !(excludedObject != null && sameMetadataObject(overriddenObject, excludedObject)) + && appliesToThisCatalog(overriddenObject) + && effectiveOwner.isPresent() + && effectiveOwner.get().type() == principalType + && principalName.equals(effectiveOwner.get().name())) { + active.addAll( + KafkaPrivilegeMapper.ownerAclBindings(overriddenObject, kafkaPrincipal, properties)); + } + } + + return active; + } + + private Set<AclBinding> bindingsForRoles(List<Role> roles, String kafkaPrincipal) { + return bindingsForRolesExcludingObject(roles, kafkaPrincipal, null); + } + + private Set<AclBinding> bindingsForRolesExcludingObject( + List<Role> roles, String kafkaPrincipal, @Nullable MetadataObject excludedObject) { + Set<AclBinding> bindings = new LinkedHashSet<>(); + for (Role role : roles) { + if (role == null || role.securableObjects() == null) { + continue; + } + for (SecurableObject securableObject : role.securableObjects()) { + if (excludedObject != null && sameMetadataObject(securableObject, excludedObject)) { + continue; + } + bindings.addAll(bindingsForSecurableObject(securableObject, kafkaPrincipal)); + } + } + return bindings; + } + + private Set<AclBinding> bindingsForSecurableObject( + SecurableObject securableObject, String kafkaPrincipal) { + if (securableObject == null || !appliesToThisCatalog(securableObject)) { + return Collections.emptySet(); + } + if (securableObject.privileges() == null) { + return Collections.emptySet(); + } + Set<AclBinding> bindings = new LinkedHashSet<>(); + for (Privilege privilege : securableObject.privileges()) { + if (privilege != null) { + bindings.addAll( + KafkaPrivilegeMapper.toAclBindings( + securableObject, privilege, kafkaPrincipal, properties)); + } + } + return Collections.unmodifiableSet(bindings); + } + + private void handleMetadataRemoved(MetadataObject removed) { + if (removed == null) { + return; + } + // Dropping a Gravitino Kafka catalog removes metadata registration only, not Kafka broker + // topics, so only explicit TOPIC removal deletes topic ACL bindings. + if (removed.type() == MetadataObject.Type.TOPIC && appliesToThisCatalog(removed)) { + AclBindingFilter filter = + new AclBindingFilter( + new ResourcePatternFilter(ResourceType.TOPIC, removed.name(), PatternType.LITERAL), + AccessControlEntryFilter.ANY); + Collection<AclBinding> deletedTopicAcls = + deleteAclsByFilter(Collections.singletonList(filter)); + reconcileAuxiliaryAclsAfterTopicRemoval(removed, deletedTopicAcls); + } + } + + private void reconcileAuxiliaryAclsAfterTopicRemoval( + MetadataObject removedTopic, Collection<AclBinding> deletedTopicAcls) { + if (deletedTopicAcls == null || deletedTopicAcls.isEmpty()) { + return; + } + + Map<String, EnumSet<AclOperation>> deletedOpsByPrincipal = new HashMap<>(); + for (AclBinding deleted : deletedTopicAcls) { + if (deleted == null || deleted.entry() == null) { + continue; + } + if (deleted.entry().permissionType() != AclPermissionType.ALLOW) { + continue; + } + AclOperation operation = deleted.entry().operation(); + if (operation != AclOperation.READ + && operation != AclOperation.WRITE + && operation != AclOperation.CREATE) { + continue; + } + deletedOpsByPrincipal + .computeIfAbsent(deleted.entry().principal(), k -> EnumSet.noneOf(AclOperation.class)) + .add(operation); + } + + if (deletedOpsByPrincipal.isEmpty()) { + return; + } + + String userPrefix = properties.getUserPrincipalType() + ":"; + String groupPrefix = properties.getGroupPrincipalType() + ":"; + String host = properties.getAclHost(); + ResourcePattern groupPattern = + new ResourcePattern( + ResourceType.GROUP, + properties.getConsumerGroupPattern(), + properties.getConsumerGroupPatternType()); + ResourcePattern clusterPattern = + new ResourcePattern(ResourceType.CLUSTER, Resource.CLUSTER_NAME, PatternType.LITERAL); + Map<MetadataObject, Optional<Owner>> removedOwnerOverride = + Collections.singletonMap(removedTopic, Optional.empty()); + + for (Map.Entry<String, EnumSet<AclOperation>> entry : deletedOpsByPrincipal.entrySet()) { + String kafkaPrincipal = entry.getKey(); + Owner.Type principalType; + String principalName; + if (kafkaPrincipal.startsWith(userPrefix) && kafkaPrincipal.length() > userPrefix.length()) { + principalType = Owner.Type.USER; + principalName = kafkaPrincipal.substring(userPrefix.length()); + } else if (kafkaPrincipal.startsWith(groupPrefix) + && kafkaPrincipal.length() > groupPrefix.length()) { + principalType = Owner.Type.GROUP; + principalName = kafkaPrincipal.substring(groupPrefix.length()); + } else { + continue; + } + + Set<AclBinding> candidateAuxRemovals = new LinkedHashSet<>(); + EnumSet<AclOperation> ops = entry.getValue(); + if (ops.contains(AclOperation.READ)) { + candidateAuxRemovals.add( + new AclBinding( + groupPattern, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.READ, AclPermissionType.ALLOW))); + } + if (ops.contains(AclOperation.WRITE) && properties.isIdempotentWriteAclEnabled()) { + candidateAuxRemovals.add( + new AclBinding( + clusterPattern, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.IDEMPOTENT_WRITE, AclPermissionType.ALLOW))); + } + if (ops.contains(AclOperation.CREATE)) { + candidateAuxRemovals.add( + new AclBinding( + clusterPattern, + new AccessControlEntry( + kafkaPrincipal, host, AclOperation.CREATE, AclPermissionType.ALLOW))); + } + + Set<AclBinding> activeBindings = + collectActiveAclBindingsForPrincipal( + principalType, + principalName, + kafkaPrincipal, + Collections.emptySet(), + Collections.emptyList(), + removedOwnerOverride, + removedTopic); + if (userPrefix.equals(groupPrefix)) { + Owner.Type peerType = principalType == Owner.Type.USER ? Owner.Type.GROUP : Owner.Type.USER; + activeBindings.addAll( + collectActiveAclBindingsForPrincipal( + peerType, + principalName, + kafkaPrincipal, + Collections.emptySet(), + Collections.emptyList(), + removedOwnerOverride, + removedTopic)); + } + deleteExactAcls(Sets.difference(candidateAuxRemovals, activeBindings)); + } + } + + private void handleMetadataRenamed(MetadataObject oldObj, MetadataObject newObj) { + if (oldObj == null || newObj == null) { + return; + } + if (oldObj.type() == MetadataObject.Type.METALAKE && oldObj.name().equals(this.metalake)) { + this.metalake = newObj.name(); + return; + } + if (oldObj.type() == MetadataObject.Type.CATALOG) { + String currentCatalog = resolveCatalogName(); + if (currentCatalog == null || oldObj.name().equals(currentCatalog)) { + this.catalogName = newObj.name(); + } + return; + } + if (oldObj.type() == MetadataObject.Type.TOPIC + && newObj.type() == MetadataObject.Type.TOPIC + && appliesToThisCatalog(oldObj)) { + AclBindingFilter filter = + new AclBindingFilter( + new ResourcePatternFilter(ResourceType.TOPIC, oldObj.name(), PatternType.LITERAL), + AccessControlEntryFilter.ANY); + Collection<AclBinding> existingBindings = describeAcls(filter); + if (existingBindings.isEmpty()) { + return; + } + + Set<AclBinding> renamedBindings = new LinkedHashSet<>(existingBindings.size()); + for (AclBinding binding : existingBindings) { + ResourcePattern newPattern = + new ResourcePattern(ResourceType.TOPIC, newObj.name(), binding.pattern().patternType()); + renamedBindings.add(new AclBinding(newPattern, binding.entry())); + } + createAcls(renamedBindings); + deleteExactAcls(existingBindings); + } + } + + private boolean appliesToThisCatalog(MetadataObject obj) { + String resolvedCatalog = resolveCatalogName(); + switch (obj.type()) { + case METALAKE: + return this.metalake.equals(obj.fullName()); + case CATALOG: + return resolvedCatalog == null || resolvedCatalog.equals(obj.fullName()); + case SCHEMA: + case TOPIC: + return resolvedCatalog == null || obj.fullName().startsWith(resolvedCatalog + "."); + default: + return false; + } + } + + private String resolveCatalogName() { + if (this.catalogName != null) { + return this.catalogName; + } + Long catalogId = properties.getCatalogId(); + if (catalogId != null) { + Optional<String> resolved = stateProvider.resolveCatalogName(metalake, catalogId); + if (resolved.isPresent()) { + this.catalogName = resolved.get(); + } + } + return this.catalogName; + } + + private String formatOwnerPrincipal(Owner owner) { + return formatPrincipal(owner.type(), owner.name()); + } + + private String formatPrincipal(Owner.Type type, String name) { + if (type == Owner.Type.USER) { + return properties.formatUserPrincipal(name); + } + if (type == Owner.Type.GROUP) { + return properties.formatGroupPrincipal(name); + } + throw new IllegalArgumentException("Unsupported owner type: " + type); + } + + private void createAcls(Collection<AclBinding> bindings) { + if (bindings == null || bindings.isEmpty()) { + return; + } + List<AclBinding> uniqueBindings = new ArrayList<>(new LinkedHashSet<>(bindings)); + try { + adminClient.createAcls(uniqueBindings).all().get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AuthorizationPluginException(e, "Interrupted while creating Kafka ACLs"); + } catch (ExecutionException e) { + throw new AuthorizationPluginException( + e.getCause() != null ? e.getCause() : e, + "Failed to create %d Kafka ACL binding(s)", + uniqueBindings.size()); + } + } + + private void deleteExactAcls(Collection<AclBinding> bindings) { + if (bindings == null || bindings.isEmpty()) { + return; + } + Set<AclBindingFilter> filters = new LinkedHashSet<>(bindings.size()); + for (AclBinding binding : bindings) { + filters.add(binding.toFilter()); + } + deleteAclsByFilter(filters); + } + + private void deleteAclsByPrincipal(String kafkaPrincipal) { + AccessControlEntryFilter entryFilter = + new AccessControlEntryFilter( + kafkaPrincipal, properties.getAclHost(), AclOperation.ANY, AclPermissionType.ANY); + // Scope cleanup to Kafka resources managed by Gravitino so out-of-band entries such as + // TRANSACTIONAL_ID or DELEGATION_TOKEN on shared clusters remain intact. + List<AclBindingFilter> filters = + List.of( + new AclBindingFilter( + new ResourcePatternFilter(ResourceType.TOPIC, null, PatternType.ANY), entryFilter), + new AclBindingFilter( + new ResourcePatternFilter(ResourceType.GROUP, null, PatternType.ANY), entryFilter), Review Comment: These principal-wide filters delete unrelated TOPIC/GROUP permissions and cluster operations such as CLUSTER_ACTION that this plugin never emits. Calling user/group cleanup can therefore erase ACLs provisioned externally or managed by another metalake on the same broker. Delete only bindings attributable to this catalog's grants, preserving shared bindings, or track managed ACL provenance explicitly. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
