org.apache.nifi.authorization.Authorizer Java Examples

The following examples show how to use org.apache.nifi.authorization.Authorizer. 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: 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 #2
Source File: StandardFlowServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    properties = NiFiProperties.createBasicNiFiProperties(null);



    variableRegistry = new FileBasedVariableRegistry(properties.getVariableRegistryPropertiesPaths());
    mockFlowFileEventRepository = mock(FlowFileEventRepository.class);
    authorizer = mock(Authorizer.class);
    mockAuditService = mock(AuditService.class);
    revisionManager = mock(RevisionManager.class);
    extensionManager = mock(ExtensionDiscoveringManager.class);
    flowController = FlowController.createStandaloneInstance(mockFlowFileEventRepository, properties, authorizer, mockAuditService, mockEncryptor,
                                    new VolatileBulletinRepository(), variableRegistry, mock(FlowRegistryClient.class), extensionManager);
    flowService = StandardFlowService.createStandaloneInstance(flowController, properties, mockEncryptor, revisionManager, authorizer);
}
 
Example #3
Source File: ComponentNode.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
default AuthorizationResult checkAuthorization(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) {
    // if this is a modification request and the reporting task is restricted ensure the user has elevated privileges. if this
    // is not a modification request, we just want to use the normal rules
    if (RequestAction.WRITE.equals(action) && isRestricted()) {
        final Set<Authorizable> restrictedComponentsAuthorizables = RestrictedComponentsAuthorizableFactory.getRestrictedComponentsAuthorizable(getComponentClass());

        for (final Authorizable restrictedComponentsAuthorizable : restrictedComponentsAuthorizables) {
            final AuthorizationResult result = restrictedComponentsAuthorizable.checkAuthorization(authorizer, RequestAction.WRITE, user, resourceContext);
            if (Result.Denied.equals(result.getResult())) {
                return result;
            }
        }
    }

    // defer to the base authorization check
    return ComponentAuthorizable.super.checkAuthorization(authorizer, action, user, resourceContext);
}
 
Example #4
Source File: UserGroupUtil.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the groups for the user with the specified identity. Returns null if the authorizer is not able to load user groups.
 *
 * @param authorizer the authorizer to load the groups from
 * @param userIdentity the user identity
 * @return the listing of groups for the user
 */
public static Set<String> getUserGroups(final Authorizer authorizer, final String userIdentity) {
    if (authorizer instanceof ManagedAuthorizer) {
        final ManagedAuthorizer managedAuthorizer = (ManagedAuthorizer) authorizer;
        final UserGroupProvider userGroupProvider = managedAuthorizer.getAccessPolicyProvider().getUserGroupProvider();
        final UserAndGroups userAndGroups = userGroupProvider.getUserAndGroups(userIdentity);
        final Set<Group> userGroups = userAndGroups.getGroups();

        if (userGroups == null || userGroups.isEmpty()) {
            return Collections.EMPTY_SET;
        } else {
            return userAndGroups.getGroups().stream().map(group -> group.getName()).collect(Collectors.toSet());
        }
    } else {
        return null;
    }
}
 
Example #5
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 #6
Source File: FlowController.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static FlowController createStandaloneInstance(
        final FlowFileEventRepository flowFileEventRepo,
        final NiFiProperties properties,
        final Authorizer authorizer,
        final AuditService auditService,
        final StringEncryptor encryptor,
        final BulletinRepository bulletinRepo,
        final VariableRegistry variableRegistry) {

    return new FlowController(
            flowFileEventRepo,
            properties,
            authorizer,
            auditService,
            encryptor,
            /* configuredForClustering */ false,
            /* NodeProtocolSender */ null,
            bulletinRepo,
            /* cluster coordinator */ null,
            /* heartbeat monitor */ null,
            /* leader election manager */ null,
            /* variable registry */ variableRegistry);
}
 
Example #7
Source File: DataAuthorizable.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void authorize(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) throws AccessDeniedException {
    if (user == null) {
        throw new AccessDeniedException("Unknown user.");
    }

    // authorize each element in the chain
    NiFiUser chainedUser = user;
    do {
        try {
            // perform the current user authorization
            Authorizable.super.authorize(authorizer, action, chainedUser, resourceContext);

            // go to the next user in the chain
            chainedUser = chainedUser.getChain();
        } catch (final ResourceNotFoundException e) {
            throw new AccessDeniedException("Unknown source component.");
        }
    } while (chainedUser != null);
}
 
Example #8
Source File: WriteAheadProvenanceRepository.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void initialize(final EventReporter eventReporter, final Authorizer authorizer, final ProvenanceAuthorizableFactory resourceFactory,
    final IdentifierLookup idLookup) throws IOException {
    final RecordWriterFactory recordWriterFactory = (file, idGenerator, compressed, createToc) -> {
        final TocWriter tocWriter = createToc ? new StandardTocWriter(TocUtil.getTocFile(file), false, false) : null;
        return new EventIdFirstSchemaRecordWriter(file, idGenerator, tocWriter, compressed, BLOCK_SIZE, idLookup);
    };

    final EventFileManager fileManager = new EventFileManager();
    final RecordReaderFactory recordReaderFactory = (file, logs, maxChars) -> {
        fileManager.obtainReadLock(file);
        try {
            return RecordReaders.newRecordReader(file, logs, maxChars);
        } finally {
            fileManager.releaseReadLock(file);
        }
    };

   init(recordWriterFactory, recordReaderFactory, eventReporter, authorizer, resourceFactory);
}
 
Example #9
Source File: AccessPolicyAuthorizable.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationResult checkAuthorization(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) {
    if (user == null) {
        throw new AccessDeniedException("Unknown user.");
    }

    final AuthorizationResult resourceResult = Authorizable.super.checkAuthorization(authorizer, action, user, resourceContext);

    // if we're denied from the resource try inheriting
    if (Result.Denied.equals(resourceResult.getResult())) {
        return getParentAuthorizable().checkAuthorization(authorizer, action, user, resourceContext);
    } else {
        return resourceResult;
    }
}
 
Example #10
Source File: StandardFlowService.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static StandardFlowService createClusteredInstance(
        final FlowController controller,
        final NiFiProperties nifiProperties,
        final NodeProtocolSenderListener senderListener,
        final ClusterCoordinator coordinator,
        final StringEncryptor encryptor,
        final RevisionManager revisionManager,
        final Authorizer authorizer) throws IOException {

    return new StandardFlowService(controller, nifiProperties, senderListener, encryptor, true, coordinator, revisionManager, authorizer);
}
 
Example #11
Source File: TenantsResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
public TenantsResource(NiFiServiceFacade serviceFacade, Authorizer authorizer, NiFiProperties properties, RequestReplicator requestReplicator,
    ClusterCoordinator clusterCoordinator, FlowController flowController) {
    this.serviceFacade = serviceFacade;
    this.authorizer = authorizer;
    setProperties(properties);
    setRequestReplicator(requestReplicator);
    setClusterCoordinator(clusterCoordinator);
    setFlowController(flowController);
}
 
Example #12
Source File: VolatileProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(final EventReporter eventReporter, final Authorizer authorizer, final ProvenanceAuthorizableFactory resourceFactory,
    final IdentifierLookup idLookup) throws IOException {
    if (initialized.getAndSet(true)) {
        return;
    }

    this.authorizer = authorizer;
    this.resourceFactory = resourceFactory;

    scheduledExecService.scheduleWithFixedDelay(new RemoveExpiredQueryResults(), 30L, 30L, TimeUnit.SECONDS);
}
 
Example #13
Source File: StandardConnection.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationResult checkAuthorization(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) {
    if (user == null) {
        return AuthorizationResult.denied("Unknown user.");
    }

    // check the source
    final AuthorizationResult sourceResult = getSourceAuthorizable().checkAuthorization(authorizer, action, user, resourceContext);
    if (Result.Denied.equals(sourceResult.getResult())) {
        return sourceResult;
    }

    // check the destination
    return getDestinationAuthorizable().checkAuthorization(authorizer, action, user, resourceContext);
}
 
Example #14
Source File: MonitorMemoryTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private FlowController buildFlowControllerForTest(final Map<String, String> addProps) throws Exception {
    addProps.put(NiFiProperties.PROVENANCE_REPO_IMPLEMENTATION_CLASS, MockProvenanceRepository.class.getName());
    addProps.put("nifi.remote.input.socket.port", "");
    addProps.put("nifi.remote.input.secure", "");
    final NiFiProperties nifiProperties = NiFiProperties.createBasicNiFiProperties(null, addProps);

    return FlowController.createStandaloneInstance(
            mock(FlowFileEventRepository.class),
            nifiProperties,
            mock(Authorizer.class),
            mock(AuditService.class),
            null,
            null,
            null);
}
 
Example #15
Source File: NiFiAnonymousAuthenticationProviderTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousEnabledSecure() throws Exception {
    final NiFiProperties nifiProperties = Mockito.mock(NiFiProperties.class);
    when(nifiProperties.isAnonymousAuthenticationAllowed()).thenReturn(true);

    final NiFiAnonymousAuthenticationProvider anonymousAuthenticationProvider = new NiFiAnonymousAuthenticationProvider(nifiProperties, mock(Authorizer.class));

    final NiFiAnonymousAuthenticationRequestToken authenticationRequest = new NiFiAnonymousAuthenticationRequestToken(true, StringUtils.EMPTY);

    final NiFiAuthenticationToken authentication = (NiFiAuthenticationToken) anonymousAuthenticationProvider.authenticate(authenticationRequest);
    final NiFiUserDetails userDetails = (NiFiUserDetails) authentication.getDetails();
    assertTrue(userDetails.getNiFiUser().isAnonymous());
}
 
Example #16
Source File: NiFiAnonymousAuthenticationProviderTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousDisabledNotSecure() throws Exception {
    final NiFiProperties nifiProperties = Mockito.mock(NiFiProperties.class);
    when(nifiProperties.isAnonymousAuthenticationAllowed()).thenReturn(false);

    final NiFiAnonymousAuthenticationProvider anonymousAuthenticationProvider = new NiFiAnonymousAuthenticationProvider(nifiProperties, mock(Authorizer.class));

    final NiFiAnonymousAuthenticationRequestToken authenticationRequest = new NiFiAnonymousAuthenticationRequestToken(false, StringUtils.EMPTY);

    final NiFiAuthenticationToken authentication = (NiFiAuthenticationToken) anonymousAuthenticationProvider.authenticate(authenticationRequest);
    final NiFiUserDetails userDetails = (NiFiUserDetails) authentication.getDetails();
    assertTrue(userDetails.getNiFiUser().isAnonymous());
}
 
Example #17
Source File: ConfiguredComponent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
default AuthorizationResult checkAuthorization(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) {
    // if this is a modification request and the reporting task is restricted ensure the user has elevated privileges. if this
    // is not a modification request, we just want to use the normal rules
    if (RequestAction.WRITE.equals(action) && isRestricted()) {
        final RestrictedComponentsAuthorizable restrictedComponentsAuthorizable = new RestrictedComponentsAuthorizable();
        final AuthorizationResult result = restrictedComponentsAuthorizable.checkAuthorization(authorizer, RequestAction.WRITE, user, resourceContext);
        if (Result.Denied.equals(result.getResult())) {
            return result;
        }
    }

    // defer to the base authorization check
    return ComponentAuthorizable.super.checkAuthorization(authorizer, action, user, resourceContext);
}
 
Example #18
Source File: VolatileProvenanceRepository.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(final EventReporter eventReporter, final Authorizer authorizer, final ProvenanceAuthorizableFactory resourceFactory,
    final IdentifierLookup idLookup) throws IOException {
    if (initialized.getAndSet(true)) {
        return;
    }

    this.authorizer = authorizer;
    this.resourceFactory = resourceFactory;

    scheduledExecService.scheduleWithFixedDelay(new RemoveExpiredQueryResults(), 30L, 30L, TimeUnit.SECONDS);
}
 
Example #19
Source File: AccessPolicyResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
public AccessPolicyResource(NiFiServiceFacade serviceFacade, Authorizer authorizer, NiFiProperties properties, RequestReplicator requestReplicator,
    ClusterCoordinator clusterCoordinator, FlowController flowController) {
    this.serviceFacade = serviceFacade;
    this.authorizer = authorizer;
    setProperties(properties);
    setRequestReplicator(requestReplicator);
    setClusterCoordinator(clusterCoordinator);
    setFlowController(flowController);
}
 
Example #20
Source File: ApplicationResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the specified Snippet with the specified request action.
 *
 * @param authorizer authorizer
 * @param lookup     lookup
 * @param action     action
 */
protected void authorizeSnippet(final SnippetAuthorizable snippet, final Authorizer authorizer, final AuthorizableLookup lookup, final RequestAction action,
                                final boolean authorizeReferencedServices, final boolean authorizeTransitiveServices) {

    final Consumer<Authorizable> authorize = authorizable -> authorizable.authorize(authorizer, action, NiFiUserUtils.getNiFiUser());

    // authorize each component in the specified snippet
    snippet.getSelectedProcessGroups().stream().forEach(processGroupAuthorizable -> {
        // note - we are not authorizing templates or controller services as they are not considered when using this snippet. however,
        // referenced services are considered so those are explicitly authorized when authorizing a processor
        authorizeProcessGroup(processGroupAuthorizable, authorizer, lookup, action, authorizeReferencedServices, false, false, authorizeTransitiveServices);
    });
    snippet.getSelectedRemoteProcessGroups().stream().forEach(authorize);
    snippet.getSelectedProcessors().stream().forEach(processorAuthorizable -> {
        // authorize the processor
        authorize.accept(processorAuthorizable.getAuthorizable());

        // authorize any referenced services if necessary
        if (authorizeReferencedServices) {
            AuthorizeControllerServiceReference.authorizeControllerServiceReferences(processorAuthorizable, authorizer, lookup, authorizeTransitiveServices);
        }
    });
    snippet.getSelectedInputPorts().stream().forEach(authorize);
    snippet.getSelectedOutputPorts().stream().forEach(authorize);
    snippet.getSelectedConnections().stream().forEach(connAuth -> authorize.accept(connAuth.getAuthorizable()));
    snippet.getSelectedFunnels().stream().forEach(authorize);
    snippet.getSelectedLabels().stream().forEach(authorize);
}
 
Example #21
Source File: StandardFlowService.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static StandardFlowService createStandaloneInstance(
        final FlowController controller,
        final NiFiProperties nifiProperties,
        final StringEncryptor encryptor,
        final RevisionManager revisionManager,
        final Authorizer authorizer) throws IOException {

    return new StandardFlowService(controller, nifiProperties, null, encryptor, false, null, revisionManager, authorizer);
}
 
Example #22
Source File: StandardFlowService.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static StandardFlowService createClusteredInstance(
        final FlowController controller,
        final NiFiProperties nifiProperties,
        final NodeProtocolSenderListener senderListener,
        final ClusterCoordinator coordinator,
        final StringEncryptor encryptor,
        final RevisionManager revisionManager,
        final Authorizer authorizer) throws IOException {

    return new StandardFlowService(controller, nifiProperties, senderListener, encryptor, true, coordinator, revisionManager, authorizer);
}
 
Example #23
Source File: FlowController.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static FlowController createClusteredInstance(
        final FlowFileEventRepository flowFileEventRepo,
        final NiFiProperties properties,
        final Authorizer authorizer,
        final AuditService auditService,
        final StringEncryptor encryptor,
        final NodeProtocolSender protocolSender,
        final BulletinRepository bulletinRepo,
        final ClusterCoordinator clusterCoordinator,
        final HeartbeatMonitor heartbeatMonitor,
        final LeaderElectionManager leaderElectionManager,
        final VariableRegistry variableRegistry) {

    final FlowController flowController = new FlowController(
            flowFileEventRepo,
            properties,
            authorizer,
            auditService,
            encryptor,
            /* configuredForClustering */ true,
            protocolSender,
            bulletinRepo,
            clusterCoordinator,
            heartbeatMonitor,
            leaderElectionManager,
            variableRegistry);

    return flowController;
}
 
Example #24
Source File: OperationAuthorizable.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Authorize the request operation action with the resource using base authorizable and operation authorizable combination.</p>
 *
 * <p>This method authorizes the request with the base authorizable first with WRITE action. If the request is allowed, then finish authorization.
 * If the base authorizable denies the request, then it checks if the user has WRITE permission for '/operation/{componentType}/{id}'.</p>
 */
public static void authorizeOperation(final Authorizable baseAuthorizable, final Authorizer authorizer, final NiFiUser user) {
    try {
        baseAuthorizable.authorize(authorizer, RequestAction.WRITE, user);
    } catch (AccessDeniedException e) {
        logger.debug("Authorization failed with {}. Try authorizing with OperationAuthorizable.", baseAuthorizable, e);
        // Always use WRITE action for operation.
        new OperationAuthorizable(baseAuthorizable).authorize(authorizer, RequestAction.WRITE, user);
    }

}
 
Example #25
Source File: ComponentMockUtil.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static void setAuthorized(final Authorizable authorizable, final boolean isAuthorized) {
    Mockito.when(authorizable.isAuthorized(
            Mockito.any(Authorizer.class),
            Mockito.any(RequestAction.class),
            AdditionalMatchers.or(Mockito.any(NiFiUser.class), Mockito.isNull()))
    ).thenReturn(isAuthorized);
}
 
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: TemplateResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
public void setAuthorizer(Authorizer authorizer) {
    this.authorizer = authorizer;
}
 
Example #28
Source File: ParameterContextResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
public void setAuthorizer(Authorizer authorizer) {
    this.authorizer = authorizer;
}
 
Example #29
Source File: CountersResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
public void setAuthorizer(Authorizer authorizer) {
    this.authorizer = authorizer;
}
 
Example #30
Source File: FlowFileQueueResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public void setAuthorizer(final Authorizer authorizer) {
    this.authorizer = authorizer;
}