org.apache.nifi.authorization.AuthorizationRequest Java Examples

The following examples show how to use org.apache.nifi.authorization.AuthorizationRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProvenanceResource.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void authorizeProvenanceRequest() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getProvenanceResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to query provenance.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #2
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    testProcessorAuthorizable = mock(Authorizable.class);
    when(testProcessorAuthorizable.getParentAuthorizable()).thenReturn(null);
    when(testProcessorAuthorizable.getResource()).thenReturn(ResourceFactory.getComponentResource(ResourceType.Processor, "id", "name"));

    testAuthorizer = mock(Authorizer.class);
    when(testAuthorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgumentAt(0, AuthorizationRequest.class);

        if (IDENTITY_1.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else if (PROXY_1.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else if (PROXY_2.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        }

        return AuthorizationResult.denied();
    });

    testDataAuthorizable = new DataAuthorizable(testProcessorAuthorizable);
}
 
Example #3
Source File: NiFiFlowTestAuthorizer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public AuthorizationResult authorize(AuthorizationRequest request) throws AuthorizationAccessException {
    // allow proxy
    if (ResourceFactory.getProxyResource().getIdentifier().equals(request.getResource().getIdentifier()) && PROXY_DN.equals(request.getIdentity())) {
        return AuthorizationResult.approved();
    }

    // read access
    if (READ_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.READ.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    // write access
    if (WRITE_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.WRITE.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    return AuthorizationResult.denied();
}
 
Example #4
Source File: ResourceResource.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void authorizeResource() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getResourceResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to retrieve resources.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #5
Source File: RangerNiFiAuthorizer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void auditAccessAttempt(final AuthorizationRequest request, final AuthorizationResult result) {
    final RangerAccessResult rangerResult;
    synchronized (resultLookup) {
        rangerResult = resultLookup.remove(request);
    }

    if (rangerResult != null && rangerResult.getIsAudited()) {
        AuthzAuditEvent event = defaultAuditHandler.getAuthzEvents(rangerResult);

        // update the event with the originally requested resource
        event.setResourceType(RANGER_NIFI_RESOURCE_NAME);
        event.setResourcePath(request.getRequestedResource().getIdentifier());

        defaultAuditHandler.logAuthzAudit(event);
    }
}
 
Example #6
Source File: TestStandardPublicPort.java    From nifi with Apache License 2.0 6 votes vote down vote up
private PublicPort createPublicPort(NiFiProperties nifiProperties) {
    final BulletinRepository bulletinRepository = mock(BulletinRepository.class);
    final ProcessScheduler processScheduler = null;

    final Authorizer authorizer = mock(Authorizer.class);
    doAnswer(invocation -> {
        final AuthorizationRequest request = invocation.getArgument(0);
        if ("[email protected]".equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else if ("[email protected]".equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        }
        return AuthorizationResult.denied();
    }).when(authorizer).authorize(any(AuthorizationRequest.class));

    final ProcessGroup processGroup = mock(ProcessGroup.class);
    doReturn("process-group-id").when(processGroup).getIdentifier();

    final StandardPublicPort port = new StandardPublicPort("id", "name",
        TransferDirection.SEND, ConnectableType.INPUT_PORT, authorizer, bulletinRepository, processScheduler, true,
        nifiProperties.getBoredYieldDuration(), IdentityMappingUtil.getIdentityMappings(nifiProperties));
    port.setProcessGroup(processGroup);
    return port;
}
 
Example #7
Source File: SystemDiagnosticsResource.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void authorizeSystem() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getSystemResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to view system diagnostics.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #8
Source File: NiFiFlowTestAuthorizer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public AuthorizationResult authorize(AuthorizationRequest request) throws AuthorizationAccessException {
    // allow proxy
    if (ResourceFactory.getProxyResource().getIdentifier().equals(request.getResource().getIdentifier()) && PROXY_DN.equals(request.getIdentity())) {
        return AuthorizationResult.approved();
    }

    // read access
    if (READ_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.READ.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    // write access
    if (WRITE_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.WRITE.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    return AuthorizationResult.denied();
}
 
Example #9
Source File: DataAuthorizableTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    testProcessorAuthorizable = mock(Authorizable.class);
    when(testProcessorAuthorizable.getParentAuthorizable()).thenReturn(null);
    when(testProcessorAuthorizable.getResource()).thenReturn(ResourceFactory.getComponentResource(ResourceType.Processor, "id", "name"));

    testAuthorizer = mock(Authorizer.class);
    when(testAuthorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgument(0);

        if (IDENTITY_1.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else if (PROXY_1.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else if (PROXY_2.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        }

        return AuthorizationResult.denied();
    });

    testDataAuthorizable = new DataAuthorizable(testProcessorAuthorizable);
}
 
Example #10
Source File: TestStandardRootGroupPort.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private RootGroupPort createRootGroupPort(NiFiProperties nifiProperties) {
    final BulletinRepository bulletinRepository = mock(BulletinRepository.class);
    final ProcessScheduler processScheduler = null;

    final Authorizer authorizer = mock(Authorizer.class);
    doAnswer(invocation -> {
        final AuthorizationRequest request = invocation.getArgumentAt(0, AuthorizationRequest.class);
        if ("[email protected]".equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        }
        return AuthorizationResult.denied();
    }).when(authorizer).authorize(any(AuthorizationRequest.class));

    final ProcessGroup processGroup = mock(ProcessGroup.class);
    doReturn("process-group-id").when(processGroup).getIdentifier();

    return new StandardRootGroupPort("id", "name", processGroup,
            TransferDirection.SEND, ConnectableType.INPUT_PORT, authorizer, bulletinRepository,
            processScheduler, true, nifiProperties);
}
 
Example #11
Source File: ProvenanceDataAuthorizableTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    Authorizable testProcessorAuthorizable;
    testProcessorAuthorizable = mock(Authorizable.class);
    when(testProcessorAuthorizable.getParentAuthorizable()).thenReturn(null);
    when(testProcessorAuthorizable.getResource()).thenReturn(ResourceFactory.getComponentResource(ResourceType.Processor, "id", "name"));

    testAuthorizer = mock(Authorizer.class);
    when(testAuthorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgument(0);

        if (IDENTITY_1.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        }

        return AuthorizationResult.denied();
    });

    testProvenanceDataAuthorizable = new ProvenanceDataAuthorizable(testProcessorAuthorizable);
}
 
Example #12
Source File: X509AuthenticationProviderTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    extractor = new SubjectDnX509PrincipalExtractor();

    certificateIdentityProvider = mock(X509IdentityProvider.class);
    when(certificateIdentityProvider.authenticate(any(X509Certificate[].class))).then(invocation -> {
        final X509Certificate[] certChain = invocation.getArgument(0);
        final String identity = extractor.extractPrincipal(certChain[0]).toString();

        if (INVALID_CERTIFICATE.equals(identity)) {
            throw new IllegalArgumentException();
        }

        return new AuthenticationResponse(identity, identity, TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS), "");
    });

    authorizer = mock(Authorizer.class);
    when(authorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgument(0);

        if (UNTRUSTED_PROXY.equals(request.getIdentity())) {
            return AuthorizationResult.denied();
        }

        return AuthorizationResult.approved();
    });

    x509AuthenticationProvider = new X509AuthenticationProvider(certificateIdentityProvider, authorizer, NiFiProperties.createBasicNiFiProperties(null));
}
 
Example #13
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAuthorizationUser() {
    final NiFiUser user = new StandardNiFiUser(IDENTITY_1);
    final AuthorizationResult result = testDataAuthorizable.checkAuthorization(testAuthorizer, RequestAction.READ, user, null);

    assertEquals(Result.Approved, result.getResult());
    verify(testAuthorizer, times(1)).authorize(argThat(new ArgumentMatcher<AuthorizationRequest>() {
        @Override
        public boolean matches(Object o) {
            return IDENTITY_1.equals(((AuthorizationRequest) o).getIdentity());
        }
    }));
}
 
Example #14
Source File: DataAuthorizableTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedUserChain() {
    final NiFiUser proxy2 = new Builder().identity(PROXY_2).build();
    final NiFiUser proxy1 = new Builder().identity(PROXY_1).chain(proxy2).build();
    final NiFiUser user = new Builder().identity(IDENTITY_1).chain(proxy1).build();
    testDataAuthorizable.authorize(testAuthorizer, RequestAction.READ, user, null);

    verify(testAuthorizer, times(3)).authorize(any(AuthorizationRequest.class));
    verifyAuthorizeForUser(IDENTITY_1);
    verifyAuthorizeForUser(PROXY_1);
    verifyAuthorizeForUser(PROXY_2);
}
 
Example #15
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void verifyAuthorizeForUser(final String identity) {
    verify(testAuthorizer, times(1)).authorize(argThat(new ArgumentMatcher<AuthorizationRequest>() {
        @Override
        public boolean matches(Object o) {
            return identity.equals(((AuthorizationRequest) o).getIdentity());
        }
    }));
}
 
Example #16
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAuthorizationUserChain() {
    final NiFiUser proxy2 = new StandardNiFiUser(PROXY_2);
    final NiFiUser proxy1 = new StandardNiFiUser(PROXY_1, proxy2);
    final NiFiUser user = new StandardNiFiUser(IDENTITY_1, proxy1);
    final AuthorizationResult result = testDataAuthorizable.checkAuthorization(testAuthorizer, RequestAction.READ, user, null);

    assertEquals(Result.Approved, result.getResult());
    verify(testAuthorizer, times(3)).authorize(any(AuthorizationRequest.class));
    verifyAuthorizeForUser(IDENTITY_1);
    verifyAuthorizeForUser(PROXY_1);
    verifyAuthorizeForUser(PROXY_2);
}
 
Example #17
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedUserChain() {
    final NiFiUser proxy2 = new StandardNiFiUser(PROXY_2);
    final NiFiUser proxy1 = new StandardNiFiUser(PROXY_1, proxy2);
    final NiFiUser user = new StandardNiFiUser(IDENTITY_1, proxy1);
    testDataAuthorizable.authorize(testAuthorizer, RequestAction.READ, user, null);

    verify(testAuthorizer, times(3)).authorize(any(AuthorizationRequest.class));
    verifyAuthorizeForUser(IDENTITY_1);
    verifyAuthorizeForUser(PROXY_1);
    verifyAuthorizeForUser(PROXY_2);
}
 
Example #18
Source File: DataAuthorizableTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedUser() {
    final NiFiUser user = new StandardNiFiUser(IDENTITY_1);
    testDataAuthorizable.authorize(testAuthorizer, RequestAction.READ, user, null);

    verify(testAuthorizer, times(1)).authorize(argThat(new ArgumentMatcher<AuthorizationRequest>() {
        @Override
        public boolean matches(Object o) {
            return IDENTITY_1.equals(((AuthorizationRequest) o).getIdentity());
        }
    }));
}
 
Example #19
Source File: DataAuthorizableTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAuthorizationUserChain() {
    final NiFiUser proxy2 = new Builder().identity(PROXY_2).build();
    final NiFiUser proxy1 = new Builder().identity(PROXY_1).chain(proxy2).build();
    final NiFiUser user = new Builder().identity(IDENTITY_1).chain(proxy1).build();
    final AuthorizationResult result = testDataAuthorizable.checkAuthorization(testAuthorizer, RequestAction.READ, user, null);

    assertEquals(Result.Approved, result.getResult());
    verify(testAuthorizer, times(3)).authorize(any(AuthorizationRequest.class));
    verifyAuthorizeForUser(IDENTITY_1);
    verifyAuthorizeForUser(PROXY_1);
    verifyAuthorizeForUser(PROXY_2);
}
 
Example #20
Source File: StandardNiFiWebConfigurationContext.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void authorizeFlowAccess(final NiFiUser user) {
    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Map<String,String> userContext;
        if (!StringUtils.isBlank(user.getClientAddress())) {
            userContext = new HashMap<>();
            userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
        } else {
            userContext = null;
        }

        final AuthorizationRequest request = new AuthorizationRequest.Builder()
                .resource(ResourceFactory.getFlowResource())
                .identity(user.getIdentity())
                .anonymous(user.isAnonymous())
                .accessAttempt(true)
                .action(RequestAction.READ)
                .userContext(userContext)
                .explanationSupplier(() -> "Unable to view the user interface.")
                .build();

        final AuthorizationResult result = authorizer.authorize(request);
        if (!Result.Approved.equals(result.getResult())) {
            throw new AccessDeniedException(result.getExplanation());
        }
    });
}
 
Example #21
Source File: CountersResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to the flow.
 */
private void authorizeCounters(final RequestAction action) {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getCountersResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(action)
            .userContext(userContext)
            .explanationSupplier(() -> {
                final StringBuilder explanation = new StringBuilder("Unable to ");

                if (RequestAction.READ.equals(action)) {
                    explanation.append("view ");
                } else {
                    explanation.append("modify ");
                }
                explanation.append("counters.");

                return explanation.toString();
            })
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #22
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to the flow.
 */
private void authorizeFlow() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getFlowResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to view the user interface.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #23
Source File: SiteToSiteResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to Site To Site details.
 * <p>
 * Note: Protected for testing purposes
 */
protected void authorizeSiteToSite() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getSiteToSiteResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to retrieve site to site details.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #24
Source File: ControllerResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to the flow.
 */
private void authorizeController(final RequestAction action) {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getControllerResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(action)
            .userContext(userContext)
            .explanationSupplier(() -> {
                final StringBuilder explanation = new StringBuilder("Unable to ");

                if (RequestAction.READ.equals(action)) {
                    explanation.append("view ");
                } else {
                    explanation.append("modify ");
                }
                explanation.append("the controller.");

                return explanation.toString();
            })
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #25
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures the specified user has permission to access the specified port. This method does
 * not utilize the DataTransferAuthorizable as that will enforce the entire chain is
 * authorized for the transfer. This method is only invoked when obtaining the site to site
 * details so the entire chain isn't necessary.
 */
private boolean isUserAuthorized(final NiFiUser user, final RootGroupPort port) {
    final boolean isSiteToSiteSecure = Boolean.TRUE.equals(properties.isSiteToSiteSecure());

    // if site to site is not secure, allow all users
    if (!isSiteToSiteSecure) {
        return true;
    }

    final Map<String, String> userContext;
    if (user.getClientAddress() != null && !user.getClientAddress().trim().isEmpty()) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getDataTransferResource(port.getResource()))
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(false)
            .action(RequestAction.WRITE)
            .userContext(userContext)
            .explanationSupplier(() -> "Unable to retrieve port details.")
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    return Result.Approved.equals(result.getResult());
}
 
Example #26
Source File: X509AuthenticationProviderTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    extractor = new SubjectDnX509PrincipalExtractor();

    certificateIdentityProvider = mock(X509IdentityProvider.class);
    when(certificateIdentityProvider.authenticate(any(X509Certificate[].class))).then(invocation -> {
        final X509Certificate[] certChain = invocation.getArgumentAt(0, X509Certificate[].class);
        final String identity = extractor.extractPrincipal(certChain[0]).toString();

        if (INVALID_CERTIFICATE.equals(identity)) {
            throw new IllegalArgumentException();
        }

        return new AuthenticationResponse(identity, identity, TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS), "");
    });

    authorizer = mock(Authorizer.class);
    when(authorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgumentAt(0, AuthorizationRequest.class);

        if (UNTRUSTED_PROXY.equals(request.getIdentity())) {
            return AuthorizationResult.denied();
        }

        return AuthorizationResult.approved();
    });

    x509AuthenticationProvider = new X509AuthenticationProvider(certificateIdentityProvider, authorizer, NiFiProperties.createBasicNiFiProperties(null, null));
}
 
Example #27
Source File: Authorizable.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the current user for the specified action on the specified resource. This method does imply the user is
 * directly accessing the specified resource.
 *
 * @param authorizer authorizer
 * @param action action
 * @param user user
 * @param resourceContext resource context
 */
default void authorize(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) throws AccessDeniedException {
    if (user == null) {
        throw new AccessDeniedException("Unknown user.");
    }

    final Map<String,String> userContext;
    if (user.getClientAddress() != null && !user.getClientAddress().trim().isEmpty()) {
        userContext = new HashMap<>();
        userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
        userContext = null;
    }

    final Resource resource = getResource();
    final AuthorizationRequest request = new AuthorizationRequest.Builder()
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(action)
            .resource(resource)
            .resourceContext(resourceContext)
            .userContext(userContext)
            .explanationSupplier(() -> {
                // build the safe explanation
                final StringBuilder safeDescription = new StringBuilder("Unable to ");

                if (RequestAction.READ.equals(action)) {
                    safeDescription.append("view ");
                } else {
                    safeDescription.append("modify ");
                }
                safeDescription.append(resource.getSafeDescription()).append(".");

                return safeDescription.toString();
            })
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (Result.ResourceNotFound.equals(result.getResult())) {
        final Authorizable parent = getParentAuthorizable();
        if (parent == null) {
            throw new AccessDeniedException("No applicable policies could be found.");
        } else {
            // create a custom authorizable to override the safe description but still defer to the parent authorizable
            final Authorizable parentProxy = new Authorizable() {
                @Override
                public Authorizable getParentAuthorizable() {
                    return parent.getParentAuthorizable();
                }

                @Override
                public Resource getResource() {
                    final Resource parentResource = parent.getResource();
                    return new Resource() {
                        @Override
                        public String getIdentifier() {
                            return parentResource.getIdentifier();
                        }

                        @Override
                        public String getName() {
                            return parentResource.getName();
                        }

                        @Override
                        public String getSafeDescription() {
                            return resource.getSafeDescription();
                        }
                    };
                }
            };
            parentProxy.authorize(authorizer, action, user, resourceContext);
        }
    } else if (Result.Denied.equals(result.getResult())) {
        throw new AccessDeniedException(result.getExplanation());
    }
}
 
Example #28
Source File: NiFiTestAuthorizer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResult authorize(AuthorizationRequest request) throws AuthorizationAccessException {
    // allow proxy
    if (ResourceFactory.getProxyResource().getIdentifier().equals(request.getResource().getIdentifier()) && PROXY_DN.equals(request.getIdentity())) {
        return AuthorizationResult.approved();
    }

    // allow flow for all users unless explicitly disable
    if (ResourceFactory.getFlowResource().getIdentifier().equals(request.getResource().getIdentifier())) {
        return AuthorizationResult.approved();
    }

    // no policy to test inheritance
    if (NO_POLICY_COMPONENT_NAME.equals(request.getResource().getName())) {
        return AuthorizationResult.resourceNotFound();
    }

    // allow the token user
    if (TOKEN_USER.equals(request.getIdentity())) {
        return AuthorizationResult.approved();
    }

    // restricted component access
    if (ResourceFactory.getRestrictedComponentsResource().getIdentifier().equals(request.getResource().getIdentifier())) {
        if (PRIVILEGED_USER_DN.equals(request.getIdentity())) {
            return AuthorizationResult.approved();
        } else {
            return AuthorizationResult.denied();
        }
    }

    // read access
    if (READ_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity()) || PRIVILEGED_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.READ.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    // write access
    if (WRITE_USER_DN.equals(request.getIdentity()) || READ_WRITE_USER_DN.equals(request.getIdentity()) || PRIVILEGED_USER_DN.equals(request.getIdentity())) {
        if (RequestAction.WRITE.equals(request.getAction())) {
            return AuthorizationResult.approved();
        }
    }

    return AuthorizationResult.denied();
}
 
Example #29
Source File: RangerNiFiAuthorizer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResult authorize(final AuthorizationRequest request) throws AuthorizationAccessException {
    final String identity = request.getIdentity();
    final String resourceIdentifier = request.getResource().getIdentifier();

    // if a ranger admin identity was provided, and it equals the identity making the request,
    // and the request is to retrieve the resources, then allow it through
    if (StringUtils.isNotBlank(rangerAdminIdentity) && rangerAdminIdentity.equals(identity)
            && resourceIdentifier.equals(RESOURCES_RESOURCE)) {
        return AuthorizationResult.approved();
    }

    final String clientIp;
    if (request.getUserContext() != null) {
        clientIp = request.getUserContext().get(UserContextKeys.CLIENT_ADDRESS.name());
    } else {
        clientIp = null;
    }

    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RANGER_NIFI_RESOURCE_NAME, resourceIdentifier);

    final RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
    rangerRequest.setResource(resource);
    rangerRequest.setAction(request.getAction().name());
    rangerRequest.setAccessType(request.getAction().name());
    rangerRequest.setUser(identity);
    rangerRequest.setAccessTime(new Date());

    if (!StringUtils.isBlank(clientIp)) {
        rangerRequest.setClientIPAddress(clientIp);
    }

    // for a direct access request use the default audit handler so we generate audit logs
    // for non-direct access provide a null result processor so no audit logs get generated
    final RangerAccessResultProcessor resultProcessor = request.isAccessAttempt() ?  defaultAuditHandler : null;

    final RangerAccessResult result = nifiPlugin.isAccessAllowed(rangerRequest, resultProcessor);

    if (result != null && result.getIsAllowed()) {
        return AuthorizationResult.approved();
    } else {
        // if result.getIsAllowed() is false, then we need to determine if it was because no policy exists for the
        // given resource, or if it was because a policy exists but not for the given user or action
        final boolean doesPolicyExist = nifiPlugin.doesPolicyExist(request.getResource().getIdentifier());

        if (doesPolicyExist) {
            final String reason = result == null ? null : result.getReason();
            if (reason != null) {
                logger.debug(String.format("Unable to authorize %s due to %s", identity, reason));
            }

            // a policy does exist for the resource so we were really denied access here
            return AuthorizationResult.denied(request.getExplanationSupplier().get());
        } else {
            // a policy doesn't exist so return resource not found so NiFi can work back up the resource hierarchy
            return AuthorizationResult.resourceNotFound();
        }
    }
}
 
Example #30
Source File: TestRangerNiFiAuthorizer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Test
@Ignore
public void testIntegration() {
    final AuthorizerInitializationContext initializationContext = Mockito.mock(AuthorizerInitializationContext.class);
    final AuthorizerConfigurationContext configurationContext = Mockito.mock(AuthorizerConfigurationContext.class);

    when(configurationContext.getProperty(eq(RangerNiFiAuthorizer.RANGER_SECURITY_PATH_PROP)))
            .thenReturn(new MockPropertyValue("src/test/resources/ranger/ranger-nifi-security.xml"));

    when(configurationContext.getProperty(eq(RangerNiFiAuthorizer.RANGER_AUDIT_PATH_PROP)))
            .thenReturn(new MockPropertyValue("src/test/resources/ranger/ranger-nifi-audit.xml"));

    Authorizer authorizer = new RangerNiFiAuthorizer();
    try {
        authorizer.initialize(initializationContext);
        authorizer.onConfigured(configurationContext);

        final AuthorizationRequest request = new AuthorizationRequest.Builder()
                .resource(new Resource() {
                    @Override
                    public String getIdentifier() {
                        return "/system";
                    }

                    @Override
                    public String getName() {
                        return "/system";
                    }

                    @Override
                    public String getSafeDescription() {
                        return "system";
                    }
                })
                .action(RequestAction.WRITE)
                .identity("admin")
                .resourceContext(new HashMap<>())
                .accessAttempt(true)
                .anonymous(false)
                .build();


        final AuthorizationResult result = authorizer.authorize(request);

        Assert.assertEquals(AuthorizationResult.denied().getResult(), result.getResult());

    } finally {
        authorizer.preDestruction();
    }
}