Search in sources :

Example 6 with AuthorizerCreationException

use of org.apache.nifi.authorization.exception.AuthorizerCreationException in project nifi by apache.

the class FileAccessPolicyProvider method convertLegacyAuthorizedUsers.

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param authorizations the current Authorizations instance that policies will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 */
private void convertLegacyAuthorizedUsers(final Authorizations authorizations) throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException("Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }
    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);
    final XMLStreamReader xsr;
    try {
        xsr = XmlUtils.createSafeReader(new StreamSource(authorizedUsersFile));
    } catch (XMLStreamException e) {
        logger.error("Encountered an error reading authorized users file: ", e);
        throw new JAXBException("Error reading authorized users file", e);
    }
    final JAXBElement<Users> element = unmarshaller.unmarshal(xsr, org.apache.nifi.user.generated.Users.class);
    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }
    // get all the user DNs into a list
    List<String> userIdentities = new ArrayList<>();
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        userIdentities.add(IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings));
    }
    // sort the list and pull out the first identity
    Collections.sort(userIdentities);
    final String seedIdentity = userIdentities.get(0);
    // create mapping from Role to access policies
    final Map<Role, Set<RoleAccessPolicy>> roleAccessPolicies = RoleAccessPolicy.getMappings(rootGroupId);
    final List<Policy> allPolicies = new ArrayList<>();
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        final User user = userGroupProvider.getUserByIdentity(legacyUserDn);
        if (user == null) {
            throw new AuthorizerCreationException("Unable to locate legacy user " + legacyUserDn + " to seed policies.");
        }
        // create policies based on the given role
        for (org.apache.nifi.user.generated.Role jaxbRole : legacyUser.getRole()) {
            Role role = Role.valueOf(jaxbRole.getName());
            Set<RoleAccessPolicy> policies = roleAccessPolicies.get(role);
            for (RoleAccessPolicy roleAccessPolicy : policies) {
                // get the matching policy, or create a new one
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, roleAccessPolicy.getResource(), roleAccessPolicy.getAction());
                // add the user to the policy if it doesn't exist
                addUserToPolicy(user.getIdentifier(), policy);
            }
        }
    }
    // convert any access controls on ports to the appropriate policies
    for (PortDTO portDTO : ports) {
        final Resource resource;
        if (portDTO.getType() != null && portDTO.getType().equals("inputPort")) {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory.getComponentResource(ResourceType.InputPort, portDTO.getId(), portDTO.getName()));
        } else {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory.getComponentResource(ResourceType.OutputPort, portDTO.getId(), portDTO.getName()));
        }
        if (portDTO.getUserAccessControl() != null) {
            for (String userAccessControl : portDTO.getUserAccessControl()) {
                // need to perform the identity mapping on the access control so it matches the identities in the User objects
                final String mappedUserAccessControl = IdentityMappingUtil.mapIdentity(userAccessControl, identityMappings);
                final User foundUser = userGroupProvider.getUserByIdentity(mappedUserAccessControl);
                // couldn't find the user matching the access control so log a warning and skip
                if (foundUser == null) {
                    logger.warn("Found port with user access control for {} but no user exists with this identity, skipping...", new Object[] { mappedUserAccessControl });
                    continue;
                }
                // we found the user so create the appropriate policy and add the user to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(), WRITE_CODE);
                addUserToPolicy(foundUser.getIdentifier(), policy);
            }
        }
        if (portDTO.getGroupAccessControl() != null) {
            for (String groupAccessControl : portDTO.getGroupAccessControl()) {
                // find a group where the name is the groupAccessControl
                Group foundGroup = null;
                for (Group group : userGroupProvider.getGroups()) {
                    if (group.getName().equals(groupAccessControl)) {
                        foundGroup = group;
                        break;
                    }
                }
                // couldn't find the group matching the access control so log a warning and skip
                if (foundGroup == null) {
                    logger.warn("Found port with group access control for {} but no group exists with this name, skipping...", new Object[] { groupAccessControl });
                    continue;
                }
                // we found the group so create the appropriate policy and add all the users to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(), WRITE_CODE);
                addGroupToPolicy(IdentifierUtil.getIdentifier(groupAccessControl), policy);
            }
        }
    }
    authorizations.getPolicies().getPolicy().addAll(allPolicies);
}
Also used : Policy(org.apache.nifi.authorization.file.generated.Policy) XMLStreamReader(javax.xml.stream.XMLStreamReader) Set(java.util.Set) HashSet(java.util.HashSet) Users(org.apache.nifi.user.generated.Users) ArrayList(java.util.ArrayList) Users(org.apache.nifi.user.generated.Users) Unmarshaller(javax.xml.bind.Unmarshaller) AuthorizerCreationException(org.apache.nifi.authorization.exception.AuthorizerCreationException) PortDTO(org.apache.nifi.web.api.dto.PortDTO) StreamSource(javax.xml.transform.stream.StreamSource) JAXBException(javax.xml.bind.JAXBException) XMLStreamException(javax.xml.stream.XMLStreamException) File(java.io.File)

Example 7 with AuthorizerCreationException

use of org.apache.nifi.authorization.exception.AuthorizerCreationException in project nifi by apache.

the class FileUserGroupProvider method convertLegacyAuthorizedUsers.

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param tenants the current Tenants instance users and groups will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 */
private void convertLegacyAuthorizedUsers(final Tenants tenants) throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException("Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }
    XMLStreamReader xsr;
    try {
        xsr = XmlUtils.createSafeReader(new StreamSource(authorizedUsersFile));
    } catch (XMLStreamException e) {
        throw new AuthorizerCreationException("Error converting the legacy authorizers file", e);
    }
    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);
    final JAXBElement<org.apache.nifi.user.generated.Users> element = unmarshaller.unmarshal(xsr, org.apache.nifi.user.generated.Users.class);
    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        org.apache.nifi.authorization.file.tenants.generated.User user = getOrCreateUser(tenants, legacyUserDn);
        // if there was a group name find or create the group and add the user to it
        org.apache.nifi.authorization.file.tenants.generated.Group group = getOrCreateGroup(tenants, legacyUser.getGroup());
        if (group != null) {
            org.apache.nifi.authorization.file.tenants.generated.Group.User groupUser = new org.apache.nifi.authorization.file.tenants.generated.Group.User();
            groupUser.setIdentifier(user.getIdentifier());
            group.getUser().add(groupUser);
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) AuthorizerCreationException(org.apache.nifi.authorization.exception.AuthorizerCreationException) StreamSource(javax.xml.transform.stream.StreamSource) Users(org.apache.nifi.authorization.file.tenants.generated.Users) XMLStreamException(javax.xml.stream.XMLStreamException) Unmarshaller(javax.xml.bind.Unmarshaller) File(java.io.File)

Example 8 with AuthorizerCreationException

use of org.apache.nifi.authorization.exception.AuthorizerCreationException in project nifi by apache.

the class FileUserGroupProvider method onConfigured.

@Override
public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException {
    try {
        final PropertyValue tenantsPath = configurationContext.getProperty(PROP_TENANTS_FILE);
        if (StringUtils.isBlank(tenantsPath.getValue())) {
            throw new AuthorizerCreationException("The users file must be specified.");
        }
        // get the tenants file and ensure it exists
        tenantsFile = new File(tenantsPath.getValue());
        if (!tenantsFile.exists()) {
            logger.info("Creating new users file at {}", new Object[] { tenantsFile.getAbsolutePath() });
            saveTenants(new Tenants());
        }
        final File tenantsFileDirectory = tenantsFile.getAbsoluteFile().getParentFile();
        // the restore directory is optional and may be null
        final File restoreDirectory = properties.getRestoreDirectory();
        if (restoreDirectory != null) {
            // sanity check that restore directory is a directory, creating it if necessary
            FileUtils.ensureDirectoryExistAndCanAccess(restoreDirectory);
            // check that restore directory is not the same as the user's directory
            if (tenantsFileDirectory.getAbsolutePath().equals(restoreDirectory.getAbsolutePath())) {
                throw new AuthorizerCreationException(String.format("Users file directory '%s' is the same as restore directory '%s' ", tenantsFileDirectory.getAbsolutePath(), restoreDirectory.getAbsolutePath()));
            }
            // the restore copy will have same file name, but reside in a different directory
            restoreTenantsFile = new File(restoreDirectory, tenantsFile.getName());
            try {
                // sync the primary copy with the restore copy
                FileUtils.syncWithRestore(tenantsFile, restoreTenantsFile, logger);
            } catch (final IOException | IllegalStateException ioe) {
                throw new AuthorizerCreationException(ioe);
            }
        }
        // extract the identity mappings from nifi.properties if any are provided
        identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));
        // get the value of the legacy authorized users file
        final PropertyValue legacyAuthorizedUsersProp = configurationContext.getProperty(FileAuthorizer.PROP_LEGACY_AUTHORIZED_USERS_FILE);
        legacyAuthorizedUsersFile = legacyAuthorizedUsersProp.isSet() ? legacyAuthorizedUsersProp.getValue() : null;
        // extract any node identities
        initialUserIdentities = new HashSet<>();
        for (Map.Entry<String, String> entry : configurationContext.getProperties().entrySet()) {
            Matcher matcher = INITIAL_USER_IDENTITY_PATTERN.matcher(entry.getKey());
            if (matcher.matches() && !StringUtils.isBlank(entry.getValue())) {
                initialUserIdentities.add(IdentityMappingUtil.mapIdentity(entry.getValue(), identityMappings));
            }
        }
        load();
        // if we've copied the authorizations file to a restore directory synchronize it
        if (restoreTenantsFile != null) {
            FileUtils.copyFile(tenantsFile, restoreTenantsFile, false, false, logger);
        }
        logger.info(String.format("Users/Groups file loaded at %s", new Date().toString()));
    } catch (IOException | AuthorizerCreationException | JAXBException | IllegalStateException | SAXException e) {
        throw new AuthorizerCreationException(e);
    }
}
Also used : Matcher(java.util.regex.Matcher) AuthorizerCreationException(org.apache.nifi.authorization.exception.AuthorizerCreationException) JAXBException(javax.xml.bind.JAXBException) PropertyValue(org.apache.nifi.components.PropertyValue) Tenants(org.apache.nifi.authorization.file.tenants.generated.Tenants) IOException(java.io.IOException) Date(java.util.Date) SAXException(org.xml.sax.SAXException) File(java.io.File) Map(java.util.Map)

Example 9 with AuthorizerCreationException

use of org.apache.nifi.authorization.exception.AuthorizerCreationException in project nifi by apache.

the class CompositeConfigurableUserGroupProvider method onConfigured.

@Override
public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException {
    final PropertyValue configurableUserGroupProviderKey = configurationContext.getProperty(PROP_CONFIGURABLE_USER_GROUP_PROVIDER);
    if (!configurableUserGroupProviderKey.isSet()) {
        throw new AuthorizerCreationException("The Configurable User Group Provider must be set.");
    }
    final UserGroupProvider userGroupProvider = userGroupProviderLookup.getUserGroupProvider(configurableUserGroupProviderKey.getValue());
    if (userGroupProvider == null) {
        throw new AuthorizerCreationException(String.format("Unable to locate the Configurable User Group Provider: %s", configurableUserGroupProviderKey));
    }
    if (!(userGroupProvider instanceof ConfigurableUserGroupProvider)) {
        throw new AuthorizerCreationException(String.format("The Configurable User Group Provider is not configurable: %s", configurableUserGroupProviderKey));
    }
    // Ensure that the ConfigurableUserGroupProvider is not also listed as one of the providers for the CompositeUserGroupProvider
    for (Map.Entry<String, String> entry : configurationContext.getProperties().entrySet()) {
        Matcher matcher = USER_GROUP_PROVIDER_PATTERN.matcher(entry.getKey());
        if (matcher.matches() && !StringUtils.isBlank(entry.getValue())) {
            final String userGroupProviderKey = entry.getValue();
            if (userGroupProviderKey.equals(configurableUserGroupProviderKey.getValue())) {
                throw new AuthorizerCreationException(String.format("Duplicate provider in Composite Configurable User Group Provider configuration: %s", userGroupProviderKey));
            }
        }
    }
    configurableUserGroupProvider = (ConfigurableUserGroupProvider) userGroupProvider;
    // configure the CompositeUserGroupProvider
    super.onConfigured(configurationContext);
}
Also used : Matcher(java.util.regex.Matcher) AuthorizerCreationException(org.apache.nifi.authorization.exception.AuthorizerCreationException) PropertyValue(org.apache.nifi.components.PropertyValue) Map(java.util.Map)

Example 10 with AuthorizerCreationException

use of org.apache.nifi.authorization.exception.AuthorizerCreationException in project nifi by apache.

the class StandardManagedAuthorizer method onConfigured.

@Override
public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException {
    final PropertyValue accessPolicyProviderKey = configurationContext.getProperty("Access Policy Provider");
    if (!accessPolicyProviderKey.isSet()) {
        throw new AuthorizerCreationException("The Access Policy Provider must be set.");
    }
    accessPolicyProvider = accessPolicyProviderLookup.getAccessPolicyProvider(accessPolicyProviderKey.getValue());
    // ensure the desired access policy provider was found
    if (accessPolicyProvider == null) {
        throw new AuthorizerCreationException(String.format("Unable to locate configured Access Policy Provider: %s", accessPolicyProviderKey));
    }
    userGroupProvider = accessPolicyProvider.getUserGroupProvider();
    // ensure the desired access policy provider has a user group provider
    if (userGroupProvider == null) {
        throw new AuthorizerCreationException(String.format("Configured Access Policy Provider %s does not contain a User Group Provider", accessPolicyProviderKey));
    }
}
Also used : AuthorizerCreationException(org.apache.nifi.authorization.exception.AuthorizerCreationException) PropertyValue(org.apache.nifi.components.PropertyValue)

Aggregations

AuthorizerCreationException (org.apache.nifi.authorization.exception.AuthorizerCreationException)20 PropertyValue (org.apache.nifi.components.PropertyValue)7 IOException (java.io.IOException)6 JAXBException (javax.xml.bind.JAXBException)5 AuthorizationAccessException (org.apache.nifi.authorization.exception.AuthorizationAccessException)5 File (java.io.File)4 Map (java.util.Map)4 Matcher (java.util.regex.Matcher)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 AuthorizerDestructionException (org.apache.nifi.authorization.exception.AuthorizerDestructionException)4 MockPropertyValue (org.apache.nifi.util.MockPropertyValue)4 NiFiProperties (org.apache.nifi.util.NiFiProperties)4 Test (org.junit.Test)4 UninheritableAuthorizationsException (org.apache.nifi.authorization.exception.UninheritableAuthorizationsException)3 SAXException (org.xml.sax.SAXException)3 KeyManagementException (java.security.KeyManagementException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 UnrecoverableKeyException (java.security.UnrecoverableKeyException)2 CertificateException (java.security.cert.CertificateException)2