Search in sources :

Example 1 with RequestAction

use of org.apache.nifi.authorization.RequestAction in project nifi by apache.

the class RangerBasePluginWithPolicies method createPolicyLookup.

private PolicyLookup createPolicyLookup(final ServicePolicies servicePolicies) {
    final Map<String, AccessPolicy> policiesByIdentifier = new HashMap<>();
    final Map<String, Map<RequestAction, AccessPolicy>> policiesByResource = new HashMap<>();
    logger.info("Converting Ranger ServicePolicies model into NiFi policy model for viewing purposes in NiFi UI.");
    servicePolicies.getPolicies().stream().forEach(policy -> {
        // only consider policies that are enabled
        if (Boolean.TRUE.equals(policy.getIsEnabled())) {
            // get all the resources for this policy - excludes/recursive support disabled
            final Set<String> resources = policy.getResources().values().stream().filter(resource -> {
                final boolean isMissingResource;
                final boolean isWildcard;
                if (resource.getValues() == null) {
                    isMissingResource = true;
                    isWildcard = false;
                } else {
                    isMissingResource = false;
                    isWildcard = resource.getValues().stream().anyMatch(value -> value.contains(WILDCARD_ASTERISK));
                }
                final boolean isExclude = Boolean.TRUE.equals(resource.getIsExcludes());
                final boolean isRecursive = Boolean.TRUE.equals(resource.getIsRecursive());
                if (isMissingResource) {
                    logger.warn("Encountered resources missing values. Skipping policy for viewing purposes. Will still be used for access decisions.");
                }
                if (isWildcard) {
                    logger.warn(String.format("Resources [%s] include a wildcard value. Skipping policy for viewing purposes. " + "Will still be used for access decisions.", StringUtils.join(resource.getValues(), ", ")));
                }
                if (isExclude) {
                    logger.warn(String.format("Resources [%s] marked as an exclude policy. Skipping policy for viewing purposes. " + "Will still be used for access decisions.", StringUtils.join(resource.getValues(), ", ")));
                }
                if (isRecursive) {
                    logger.warn(String.format("Resources [%s] marked as a recursive policy. Skipping policy for viewing purposes. " + "Will still be used for access decisions.", StringUtils.join(resource.getValues(), ", ")));
                }
                return !isMissingResource && !isWildcard && !isExclude && !isRecursive;
            }).flatMap(resource -> resource.getValues().stream()).collect(Collectors.toSet());
            policy.getPolicyItems().forEach(policyItem -> {
                // get all the users for this policy item, excluding unknown users
                final Set<String> userIds = policyItem.getUsers().stream().map(userIdentity -> getUser(userIdentity)).filter(Objects::nonNull).map(user -> user.getIdentifier()).collect(Collectors.toSet());
                // get all groups for this policy item, excluding unknown groups
                final Set<String> groupIds = policyItem.getGroups().stream().map(groupName -> getGroup(groupName)).filter(Objects::nonNull).map(group -> group.getIdentifier()).collect(Collectors.toSet());
                // check if this policy item is a delegate admin
                final boolean isDelegateAdmin = Boolean.TRUE.equals(policyItem.getDelegateAdmin());
                policyItem.getAccesses().forEach(access -> {
                    try {
                        // interpret the request action
                        final RequestAction action = RequestAction.valueOf(access.getType());
                        // function for creating an access policy
                        final Function<String, AccessPolicy> createPolicy = resource -> new AccessPolicy.Builder().identifierGenerateFromSeed(resource + access.getType()).resource(resource).action(action).addUsers(userIds).addGroups(groupIds).build();
                        resources.forEach(resource -> {
                            // create the access policy for the specified resource
                            final AccessPolicy accessPolicy = createPolicy.apply(resource);
                            policiesByIdentifier.put(accessPolicy.getIdentifier(), accessPolicy);
                            policiesByResource.computeIfAbsent(resource, r -> new HashMap<>()).put(action, accessPolicy);
                            // if this is a delegate admin, also create the admin policy for the specified resource
                            if (isDelegateAdmin) {
                                // build the admin resource identifier
                                final String adminResource;
                                if (resource.startsWith("/")) {
                                    adminResource = "/policies" + resource;
                                } else {
                                    adminResource = "/policies/" + resource;
                                }
                                final AccessPolicy adminAccessPolicy = createPolicy.apply(adminResource);
                                policiesByIdentifier.put(adminAccessPolicy.getIdentifier(), adminAccessPolicy);
                                policiesByResource.computeIfAbsent(adminResource, ar -> new HashMap<>()).put(action, adminAccessPolicy);
                            }
                        });
                    } catch (final IllegalArgumentException e) {
                        logger.warn(String.format("Unrecognized request action '%s'. Skipping policy for viewing purposes. Will still be used for access decisions.", access.getType()));
                    }
                });
            });
        }
    });
    return new PolicyLookup(policiesByIdentifier, policiesByResource);
}
Also used : Logger(org.slf4j.Logger) RequestAction(org.apache.nifi.authorization.RequestAction) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) HashMap(java.util.HashMap) Group(org.apache.nifi.authorization.Group) StringUtils(org.apache.nifi.util.StringUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ServicePolicies(org.apache.ranger.plugin.util.ServicePolicies) User(org.apache.nifi.authorization.User) UserGroupProvider(org.apache.nifi.authorization.UserGroupProvider) HashSet(java.util.HashSet) Objects(java.util.Objects) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) RangerBasePlugin(org.apache.ranger.plugin.service.RangerBasePlugin) Map(java.util.Map) AuthorizationAccessException(org.apache.nifi.authorization.exception.AuthorizationAccessException) Collections(java.util.Collections) HashMap(java.util.HashMap) RequestAction(org.apache.nifi.authorization.RequestAction) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) Objects(java.util.Objects) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with RequestAction

use of org.apache.nifi.authorization.RequestAction in project nifi by apache.

the class TestRangerNiFiAuthorizer method testDenied.

@Test
public void testDenied() {
    final String systemResource = "/system";
    final RequestAction action = RequestAction.WRITE;
    final String user = "admin";
    // the incoming NiFi request to test
    final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(new MockResource(systemResource, systemResource)).action(action).identity(user).resourceContext(new HashMap<>()).accessAttempt(true).anonymous(false).build();
    // the expected Ranger resource and request that are created
    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RangerNiFiAuthorizer.RANGER_NIFI_RESOURCE_NAME, systemResource);
    final RangerAccessRequestImpl expectedRangerRequest = new RangerAccessRequestImpl();
    expectedRangerRequest.setResource(resource);
    expectedRangerRequest.setAction(request.getAction().name());
    expectedRangerRequest.setAccessType(request.getAction().name());
    expectedRangerRequest.setUser(request.getIdentity());
    // no result processor should be provided used non-direct access
    when(rangerBasePlugin.isAccessAllowed(argThat(new RangerAccessRequestMatcher(expectedRangerRequest)))).thenReturn(notAllowedResult);
    // return true when checking if a policy exists for the resource
    when(rangerBasePlugin.doesPolicyExist(systemResource, action)).thenReturn(true);
    final AuthorizationResult result = authorizer.authorize(request);
    assertEquals(AuthorizationResult.denied().getResult(), result.getResult());
}
Also used : RangerAccessRequestImpl(org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl) AuthorizationRequest(org.apache.nifi.authorization.AuthorizationRequest) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl) RequestAction(org.apache.nifi.authorization.RequestAction) HashMap(java.util.HashMap) AuthorizationResult(org.apache.nifi.authorization.AuthorizationResult) Test(org.junit.Test)

Example 3 with RequestAction

use of org.apache.nifi.authorization.RequestAction in project nifi by apache.

the class TestRangerNiFiAuthorizer method runRangerAdminTest.

private void runRangerAdminTest(final String resourceIdentifier, final AuthorizationResult.Result expectedResult) {
    configurationContext = createMockConfigContext();
    final String rangerAdminIdentity = "ranger-admin";
    when(configurationContext.getProperty(eq(RangerNiFiAuthorizer.RANGER_ADMIN_IDENTITY_PROP))).thenReturn(new MockPropertyValue(rangerAdminIdentity));
    rangerBasePlugin = Mockito.mock(RangerBasePluginWithPolicies.class);
    authorizer = new MockRangerNiFiAuthorizer(rangerBasePlugin);
    authorizer.onConfigured(configurationContext);
    final RequestAction action = RequestAction.WRITE;
    // the incoming NiFi request to test
    final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(new MockResource(resourceIdentifier, resourceIdentifier)).action(action).identity(rangerAdminIdentity).resourceContext(new HashMap<>()).accessAttempt(true).anonymous(false).build();
    // the expected Ranger resource and request that are created
    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RangerNiFiAuthorizer.RANGER_NIFI_RESOURCE_NAME, resourceIdentifier);
    final RangerAccessRequestImpl expectedRangerRequest = new RangerAccessRequestImpl();
    expectedRangerRequest.setResource(resource);
    expectedRangerRequest.setAction(request.getAction().name());
    expectedRangerRequest.setAccessType(request.getAction().name());
    expectedRangerRequest.setUser(request.getIdentity());
    // return true when checking if a policy exists for the resource
    when(rangerBasePlugin.doesPolicyExist(resourceIdentifier, action)).thenReturn(true);
    // a non-null result processor should be used for direct access
    when(rangerBasePlugin.isAccessAllowed(argThat(new RangerAccessRequestMatcher(expectedRangerRequest)))).thenReturn(notAllowedResult);
    final AuthorizationResult result = authorizer.authorize(request);
    assertEquals(expectedResult, result.getResult());
}
Also used : RangerAccessRequestImpl(org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl) AuthorizationRequest(org.apache.nifi.authorization.AuthorizationRequest) RequestAction(org.apache.nifi.authorization.RequestAction) HashMap(java.util.HashMap) MockPropertyValue(org.apache.nifi.util.MockPropertyValue) AuthorizationResult(org.apache.nifi.authorization.AuthorizationResult) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl)

Example 4 with RequestAction

use of org.apache.nifi.authorization.RequestAction in project nifi by apache.

the class StandardNiFiServiceFacade method cleanUpPolicies.

/**
 * Clean up the policies for the specified component resource.
 *
 * @param componentResource the resource for the component
 */
private void cleanUpPolicies(final Resource componentResource) {
    // ensure the authorizer supports configuration
    if (accessPolicyDAO.supportsConfigurableAuthorizer()) {
        final List<Resource> resources = new ArrayList<>();
        resources.add(componentResource);
        resources.add(ResourceFactory.getDataResource(componentResource));
        resources.add(ResourceFactory.getDataTransferResource(componentResource));
        resources.add(ResourceFactory.getPolicyResource(componentResource));
        for (final Resource resource : resources) {
            for (final RequestAction action : RequestAction.values()) {
                try {
                    // since the component is being deleted, also delete any relevant access policies
                    final AccessPolicy readPolicy = accessPolicyDAO.getAccessPolicy(action, resource.getIdentifier());
                    if (readPolicy != null) {
                        accessPolicyDAO.deleteAccessPolicy(readPolicy.getIdentifier());
                    }
                } catch (final Exception e) {
                    logger.warn(String.format("Unable to remove access policy for %s %s after component removal.", action, resource.getIdentifier()), e);
                }
            }
        }
    }
}
Also used : RequestAction(org.apache.nifi.authorization.RequestAction) EnforcePolicyPermissionsThroughBaseResource(org.apache.nifi.authorization.resource.EnforcePolicyPermissionsThroughBaseResource) Resource(org.apache.nifi.authorization.Resource) ArrayList(java.util.ArrayList) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) IOException(java.io.IOException) UnknownNodeException(org.apache.nifi.cluster.manager.exception.UnknownNodeException) IllegalNodeDeletionException(org.apache.nifi.cluster.manager.exception.IllegalNodeDeletionException) WebApplicationException(javax.ws.rs.WebApplicationException) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) ExpiredRevisionClaimException(org.apache.nifi.web.revision.ExpiredRevisionClaimException)

Example 5 with RequestAction

use of org.apache.nifi.authorization.RequestAction in project nifi by apache.

the class TestRangerNiFiAuthorizer method testResourceNotFound.

@Test
public void testResourceNotFound() {
    final String systemResource = "/system";
    final RequestAction action = RequestAction.WRITE;
    final String user = "admin";
    // the incoming NiFi request to test
    final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(new MockResource(systemResource, systemResource)).action(action).identity(user).resourceContext(new HashMap<>()).accessAttempt(true).anonymous(false).build();
    // the expected Ranger resource and request that are created
    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RangerNiFiAuthorizer.RANGER_NIFI_RESOURCE_NAME, systemResource);
    final RangerAccessRequestImpl expectedRangerRequest = new RangerAccessRequestImpl();
    expectedRangerRequest.setResource(resource);
    expectedRangerRequest.setAction(request.getAction().name());
    expectedRangerRequest.setAccessType(request.getAction().name());
    expectedRangerRequest.setUser(request.getIdentity());
    // no result processor should be provided used non-direct access
    when(rangerBasePlugin.isAccessAllowed(argThat(new RangerAccessRequestMatcher(expectedRangerRequest)), notNull(RangerAccessResultProcessor.class))).thenReturn(notAllowedResult);
    // return false when checking if a policy exists for the resource
    when(rangerBasePlugin.doesPolicyExist(systemResource, action)).thenReturn(false);
    final AuthorizationResult result = authorizer.authorize(request);
    assertEquals(AuthorizationResult.resourceNotFound().getResult(), result.getResult());
}
Also used : RangerAccessResultProcessor(org.apache.ranger.plugin.policyengine.RangerAccessResultProcessor) RangerAccessRequestImpl(org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl) AuthorizationRequest(org.apache.nifi.authorization.AuthorizationRequest) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl) RequestAction(org.apache.nifi.authorization.RequestAction) HashMap(java.util.HashMap) AuthorizationResult(org.apache.nifi.authorization.AuthorizationResult) Test(org.junit.Test)

Aggregations

RequestAction (org.apache.nifi.authorization.RequestAction)10 HashMap (java.util.HashMap)7 AuthorizationRequest (org.apache.nifi.authorization.AuthorizationRequest)5 AuthorizationResult (org.apache.nifi.authorization.AuthorizationResult)5 RangerAccessRequestImpl (org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl)5 RangerAccessResourceImpl (org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl)5 AccessPolicy (org.apache.nifi.authorization.AccessPolicy)4 Test (org.junit.Test)4 Resource (org.apache.nifi.authorization.Resource)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiResponses (io.swagger.annotations.ApiResponses)1 IOException (java.io.IOException)1 Collections (java.util.Collections)1 LinkedHashSet (java.util.LinkedHashSet)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Set (java.util.Set)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1