Search in sources :

Example 1 with User

use of org.apache.nifi.registry.security.authorization.User in project nifi-registry by apache.

the class LdapUserGroupProvider method load.

/**
 * Reloads the tenants.
 */
private void load(final ContextSource contextSource) {
    // create the ldapTemplate based on the context source. use a single source context to use the same connection
    // to support paging when configured
    final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
    try {
        final List<User> userList = new ArrayList<>();
        final List<Group> groupList = new ArrayList<>();
        // group dn -> user identifiers lookup
        final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();
        // user dn -> user lookup
        final Map<String, User> userLookup = new HashMap<>();
        if (performUserSearch) {
            // search controls
            final SearchControls userControls = new SearchControls();
            userControls.setSearchScope(userSearchScope.ordinal());
            // consider paging support for users
            final DirContextProcessor userProcessor;
            if (pageSize == null) {
                userProcessor = new NullDirContextProcessor();
            } else {
                userProcessor = new PagedResultsDirContextProcessor(pageSize);
            }
            // looking for objects matching the user object class
            final AndFilter userFilter = new AndFilter();
            userFilter.and(new EqualsFilter("objectClass", userObjectClass));
            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(userSearchFilter)) {
                userFilter.and(new HardcodedFilter(userSearchFilter));
            }
            do {
                userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() {

                    @Override
                    protected User doMapFromContext(DirContextOperations ctx) {
                        // get the user identity
                        final String identity = getUserIdentity(ctx);
                        // build the user
                        final User user = new User.Builder().identifierGenerateFromSeed(identity).identity(identity).build();
                        // store the user for group member later
                        userLookup.put(getReferencedUserValue(ctx), user);
                        if (StringUtils.isNotBlank(userGroupNameAttribute)) {
                            final Attribute attributeGroups = ctx.getAttributes().get(userGroupNameAttribute);
                            if (attributeGroups == null) {
                                logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership.");
                            } else {
                                try {
                                    final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups.getAll();
                                    while (groupValues.hasMoreElements()) {
                                        // store the group -> user identifier mapping
                                        groupToUserIdentifierMappings.computeIfAbsent(groupValues.next(), g -> new HashSet<>()).add(user.getIdentifier());
                                    }
                                } catch (NamingException e) {
                                    throw new AuthorizationAccessException("Error while retrieving user group name attribute [" + userIdentityAttribute + "].");
                                }
                            }
                        }
                        return user;
                    }
                }, userProcessor));
            } while (hasMorePages(userProcessor));
        }
        if (performGroupSearch) {
            final SearchControls groupControls = new SearchControls();
            groupControls.setSearchScope(groupSearchScope.ordinal());
            // consider paging support for groups
            final DirContextProcessor groupProcessor;
            if (pageSize == null) {
                groupProcessor = new NullDirContextProcessor();
            } else {
                groupProcessor = new PagedResultsDirContextProcessor(pageSize);
            }
            // looking for objects matching the group object class
            AndFilter groupFilter = new AndFilter();
            groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));
            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(groupSearchFilter)) {
                groupFilter.and(new HardcodedFilter(groupSearchFilter));
            }
            do {
                groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() {

                    @Override
                    protected Group doMapFromContext(DirContextOperations ctx) {
                        final String dn = ctx.getDn().toString();
                        // get the group identity
                        final String name = getGroupName(ctx);
                        // get the value of this group that may associate it to users
                        final String referencedGroupValue = getReferencedGroupValue(ctx);
                        if (!StringUtils.isBlank(groupMemberAttribute)) {
                            Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
                            if (attributeUsers == null) {
                                logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership.");
                            } else {
                                try {
                                    final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers.getAll();
                                    while (userValues.hasMoreElements()) {
                                        final String userValue = userValues.next();
                                        if (performUserSearch) {
                                            // find the user by it's referenced attribute and add the identifier to this group
                                            final User user = userLookup.get(userValue);
                                            // ensure the user is known
                                            if (user != null) {
                                                groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
                                            } else {
                                                logger.warn(String.format("%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue));
                                            }
                                        } else {
                                            // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
                                            final String userDn = userValue;
                                            final String userIdentity;
                                            if (useDnForUserIdentity) {
                                                // use the user value to avoid the unnecessary look up
                                                userIdentity = userDn;
                                            } else {
                                                // lookup the user to extract the user identity
                                                userIdentity = getUserIdentity((DirContextAdapter) ldapTemplate.lookup(userDn));
                                            }
                                            // build the user
                                            final User user = new User.Builder().identifierGenerateFromSeed(userIdentity).identity(userIdentity).build();
                                            // add this user
                                            userList.add(user);
                                            groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
                                        }
                                    }
                                } catch (NamingException e) {
                                    throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
                                }
                            }
                        }
                        // build this group
                        final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(name).name(name);
                        // add all users that were associated with this referenced group attribute
                        if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
                            groupToUserIdentifierMappings.remove(referencedGroupValue).forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                        }
                        return groupBuilder.build();
                    }
                }, groupProcessor));
            } while (hasMorePages(groupProcessor));
            // any remaining groupDn's were referenced by a user but not found while searching groups
            groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
                logger.warn(String.format("[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
            });
        } else {
            // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn
            // groups are not being searched so lookup any groups identified while searching users
            groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
                final String groupName;
                if (useDnForGroupName) {
                    // use the dn to avoid the unnecessary look up
                    groupName = groupDn;
                } else {
                    groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
                }
                // define the group
                final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName).name(groupName);
                // add each user
                userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                // build the group
                groupList.add(groupBuilder.build());
            });
        }
        // record the updated tenants
        tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
    } finally {
        singleContextSource.destroy();
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) AbstractContextMapper(org.springframework.ldap.core.support.AbstractContextMapper) AndFilter(org.springframework.ldap.filter.AndFilter) ClientAuth(org.apache.nifi.registry.security.util.SslContextFactory.ClientAuth) LoggerFactory(org.slf4j.LoggerFactory) LdapTemplate(org.springframework.ldap.core.LdapTemplate) NamingException(javax.naming.NamingException) KeyStoreException(java.security.KeyStoreException) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(javax.naming.directory.Attribute) Map(java.util.Map) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) ThreadFactory(java.util.concurrent.ThreadFactory) LdapsSocketFactory(org.apache.nifi.registry.security.ldap.LdapsSocketFactory) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) AuthorizerContext(org.apache.nifi.registry.security.authorization.annotation.AuthorizerContext) UserGroupProvider(org.apache.nifi.registry.security.authorization.UserGroupProvider) Set(java.util.Set) KeyManagementException(java.security.KeyManagementException) HardcodedFilter(org.springframework.ldap.filter.HardcodedFilter) LdapAuthenticationStrategy(org.apache.nifi.registry.security.ldap.LdapAuthenticationStrategy) SslContextFactory(org.apache.nifi.registry.security.util.SslContextFactory) Executors(java.util.concurrent.Executors) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NamingEnumeration(javax.naming.NamingEnumeration) SingleContextSource(org.springframework.ldap.core.support.SingleContextSource) IdentityMapping(org.apache.nifi.registry.properties.util.IdentityMapping) DirContextOperations(org.springframework.ldap.core.DirContextOperations) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) ReferralStrategy(org.apache.nifi.registry.security.ldap.ReferralStrategy) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) DirContextProcessor(org.springframework.ldap.core.DirContextProcessor) IdentityMappingUtil(org.apache.nifi.registry.properties.util.IdentityMappingUtil) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) SearchControls(javax.naming.directory.SearchControls) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Group(org.apache.nifi.registry.security.authorization.Group) SimpleDirContextAuthenticationStrategy(org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy) UserGroupProviderInitializationContext(org.apache.nifi.registry.security.authorization.UserGroupProviderInitializationContext) NiFiRegistryProperties(org.apache.nifi.registry.properties.NiFiRegistryProperties) UserAndGroups(org.apache.nifi.registry.security.authorization.UserAndGroups) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AbstractTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.AbstractTlsDirContextAuthenticationStrategy) SecurityProviderDestructionException(org.apache.nifi.registry.security.exception.SecurityProviderDestructionException) DefaultTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy) Context(javax.naming.Context) AuthorizationAccessException(org.apache.nifi.registry.security.authorization.exception.AuthorizationAccessException) Logger(org.slf4j.Logger) ContextSource(org.springframework.ldap.core.ContextSource) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) User(org.apache.nifi.registry.security.authorization.User) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) AuthorizerConfigurationContext(org.apache.nifi.registry.security.authorization.AuthorizerConfigurationContext) PropertyValue(org.apache.nifi.registry.util.PropertyValue) Collections(java.util.Collections) FormatUtils(org.apache.nifi.registry.util.FormatUtils) Group(org.apache.nifi.registry.security.authorization.Group) User(org.apache.nifi.registry.security.authorization.User) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) DirContextProcessor(org.springframework.ldap.core.DirContextProcessor) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) LdapTemplate(org.springframework.ldap.core.LdapTemplate) AuthorizationAccessException(org.apache.nifi.registry.security.authorization.exception.AuthorizationAccessException) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) HashSet(java.util.HashSet) SingleContextSource(org.springframework.ldap.core.support.SingleContextSource) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) HardcodedFilter(org.springframework.ldap.filter.HardcodedFilter) AndFilter(org.springframework.ldap.filter.AndFilter) AbstractContextMapper(org.springframework.ldap.core.support.AbstractContextMapper) DirContextOperations(org.springframework.ldap.core.DirContextOperations)

Example 2 with User

use of org.apache.nifi.registry.security.authorization.User in project nifi-registry by apache.

the class FileUserGroupProvider method updateGroup.

@Override
public synchronized Group updateGroup(Group group) throws AuthorizationAccessException {
    if (group == null) {
        throw new IllegalArgumentException("Group cannot be null");
    }
    final UserGroupHolder holder = userGroupHolder.get();
    final Tenants tenants = holder.getTenants();
    // find the group that needs to be update
    org.apache.nifi.registry.security.authorization.file.tenants.generated.Group updateGroup = null;
    for (org.apache.nifi.registry.security.authorization.file.tenants.generated.Group jaxbGroup : tenants.getGroups().getGroup()) {
        if (jaxbGroup.getIdentifier().equals(group.getIdentifier())) {
            updateGroup = jaxbGroup;
            break;
        }
    }
    // if the group wasn't found return null, otherwise update the group and save changes
    if (updateGroup == null) {
        return null;
    }
    // reset the list of users and add each user to the group
    updateGroup.getUser().clear();
    for (String groupUser : group.getUsers()) {
        org.apache.nifi.registry.security.authorization.file.tenants.generated.Group.User jaxbGroupUser = new org.apache.nifi.registry.security.authorization.file.tenants.generated.Group.User();
        jaxbGroupUser.setIdentifier(groupUser);
        updateGroup.getUser().add(jaxbGroupUser);
    }
    updateGroup.setName(group.getName());
    saveAndRefreshHolder(tenants);
    return userGroupHolder.get().getGroupsById().get(group.getIdentifier());
}
Also used : Group(org.apache.nifi.registry.security.authorization.Group) User(org.apache.nifi.registry.security.authorization.User) Tenants(org.apache.nifi.registry.security.authorization.file.tenants.generated.Tenants)

Example 3 with User

use of org.apache.nifi.registry.security.authorization.User in project nifi-registry by apache.

the class UserGroupHolder method createGroupsByUserIdentityMap.

/**
 * Creates a Map from user identity to the set of Groups for that identity.
 *
 * @param groups all groups
 * @param users all users
 * @return a Map from User identity to the set of Groups for that identity
 */
private Map<String, Set<Group>> createGroupsByUserIdentityMap(final Set<Group> groups, final Set<User> users) {
    Map<String, Set<Group>> groupsByUserIdentity = new HashMap<>();
    for (User user : users) {
        Set<Group> userGroups = new HashSet<>();
        for (Group group : groups) {
            for (String groupUser : group.getUsers()) {
                if (groupUser.equals(user.getIdentifier())) {
                    userGroups.add(group);
                }
            }
        }
        groupsByUserIdentity.put(user.getIdentity(), userGroups);
    }
    return groupsByUserIdentity;
}
Also used : Group(org.apache.nifi.registry.security.authorization.Group) HashSet(java.util.HashSet) Set(java.util.Set) User(org.apache.nifi.registry.security.authorization.User) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 4 with User

use of org.apache.nifi.registry.security.authorization.User in project nifi-registry by apache.

the class TenantHolder method createGroupsByUserIdentityMap.

/**
 * Creates a Map from user identity to the set of Groups for that identity.
 *
 * @param groups all groups
 * @param users all users
 * @return a Map from User identity to the set of Groups for that identity
 */
private Map<String, Set<Group>> createGroupsByUserIdentityMap(final Set<Group> groups, final Set<User> users) {
    Map<String, Set<Group>> groupsByUserIdentity = new HashMap<>();
    for (User user : users) {
        Set<Group> userGroups = new HashSet<>();
        for (Group group : groups) {
            for (String groupUser : group.getUsers()) {
                if (groupUser.equals(user.getIdentifier())) {
                    userGroups.add(group);
                }
            }
        }
        groupsByUserIdentity.put(user.getIdentity(), userGroups);
    }
    return groupsByUserIdentity;
}
Also used : Group(org.apache.nifi.registry.security.authorization.Group) HashSet(java.util.HashSet) Set(java.util.Set) User(org.apache.nifi.registry.security.authorization.User) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 5 with User

use of org.apache.nifi.registry.security.authorization.User in project nifi-registry by apache.

the class FileAccessPolicyProvider method addUserToAccessPolicy.

/**
 * Creates and adds an access policy for the given resource, identity, and actions to the specified authorizations.
 *
 * @param authorizations the Authorizations instance to add the policy to
 * @param resource the resource for the policy
 * @param userIdentifier the identifier for the user to add to the policy
 * @param action the action for the policy
 */
private void addUserToAccessPolicy(final Authorizations authorizations, final String resource, final String userIdentifier, final String action) {
    // first try to find an existing policy for the given resource and action
    Policy foundPolicy = null;
    for (Policy policy : authorizations.getPolicies().getPolicy()) {
        if (policy.getResource().equals(resource) && policy.getAction().equals(action)) {
            foundPolicy = policy;
            break;
        }
    }
    if (foundPolicy == null) {
        // if we didn't find an existing policy create a new one
        final String uuidSeed = resource + action;
        final AccessPolicy.Builder builder = new AccessPolicy.Builder().identifierGenerateFromSeed(uuidSeed).resource(resource).addUser(userIdentifier);
        if (action.equals(READ_CODE)) {
            builder.action(RequestAction.READ);
        } else if (action.equals(WRITE_CODE)) {
            builder.action(RequestAction.WRITE);
        } else if (action.equals(DELETE_CODE)) {
            builder.action(RequestAction.DELETE);
        } else {
            throw new IllegalStateException("Unknown Policy Action: " + action);
        }
        final AccessPolicy accessPolicy = builder.build();
        final Policy jaxbPolicy = createJAXBPolicy(accessPolicy);
        authorizations.getPolicies().getPolicy().add(jaxbPolicy);
    } else {
        // otherwise add the user to the existing policy
        Policy.User policyUser = new Policy.User();
        policyUser.setIdentifier(userIdentifier);
        foundPolicy.getUser().add(policyUser);
    }
}
Also used : AccessPolicy(org.apache.nifi.registry.security.authorization.AccessPolicy) Policy(org.apache.nifi.registry.security.authorization.file.generated.Policy) User(org.apache.nifi.registry.security.authorization.User) AccessPolicy(org.apache.nifi.registry.security.authorization.AccessPolicy)

Aggregations

User (org.apache.nifi.registry.security.authorization.User)11 Group (org.apache.nifi.registry.security.authorization.Group)9 Tenants (org.apache.nifi.registry.security.authorization.file.tenants.generated.Tenants)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 AuthorizationAccessException (org.apache.nifi.registry.security.authorization.exception.AuthorizationAccessException)3 IOException (java.io.IOException)2 UserAndGroups (org.apache.nifi.registry.security.authorization.UserAndGroups)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 StringWriter (java.io.StringWriter)1 KeyManagementException (java.security.KeyManagementException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 UnrecoverableKeyException (java.security.UnrecoverableKeyException)1 CertificateException (java.security.cert.CertificateException)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1