org.apache.nifi.authorization.user.NiFiUser Java Examples

The following examples show how to use org.apache.nifi.authorization.user.NiFiUser. 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: PersistentProvenanceRepository.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncLineageSubmission retrieveLineageSubmission(final String lineageIdentifier, final NiFiUser user) {
    final AsyncLineageSubmission submission = lineageSubmissionMap.get(lineageIdentifier);
    final String userId = submission.getSubmitterIdentity();

    if (user == null && userId == null) {
        return submission;
    }

    if (user == null) {
        throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because no user id was provided in the lineage request.");
    }

    if (userId == null || userId.equals(user.getIdentity())) {
        return submission;
    }

    throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because " + user.getIdentity() + " is not the user who submitted the request.");
}
 
Example #2
Source File: SnippetAuditor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an audit record for the creation of the specified funnel.
 */
private FlowChangeAction generateAuditRecord(String id, String name, Component type, Operation operation, Date timestamp) {
    FlowChangeAction action = null;

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {
        // create the action for adding this funnel
        action = new FlowChangeAction();
        action.setUserIdentity(user.getIdentity());
        action.setOperation(operation);
        action.setTimestamp(timestamp);
        action.setSourceId(id);
        action.setSourceName(name);
        action.setSourceType(type);
    }

    return action;
}
 
Example #3
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public NodeDTO updateNode(final NodeDTO nodeDTO) {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new WebApplicationException(new Throwable("Unable to access details for current user."));
    }
    final String userDn = user.getIdentity();

    final NodeIdentifier nodeId = clusterCoordinator.getNodeIdentifier(nodeDTO.getNodeId());
    if (nodeId == null) {
        throw new UnknownNodeException("No node exists with ID " + nodeDTO.getNodeId());
    }


    if (NodeConnectionState.CONNECTING.name().equalsIgnoreCase(nodeDTO.getStatus())) {
        clusterCoordinator.requestNodeConnect(nodeId, userDn);
    } else if (NodeConnectionState.DISCONNECTING.name().equalsIgnoreCase(nodeDTO.getStatus())) {
        clusterCoordinator.requestNodeDisconnect(nodeId, DisconnectionCode.USER_DISCONNECTED,
                "User " + userDn + " requested that node be disconnected from cluster");
    }

    return getNode(nodeId);
}
 
Example #4
Source File: ParameterContextResource.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Response deleteValidationRequest(final String requestType, final String contextId, final String requestId, final boolean disconnectedNodeAcknowledged) {
    if (requestId == null) {
        throw new IllegalArgumentException("Request ID must be specified.");
    }

    if (isDisconnectedFromCluster()) {
        verifyDisconnectedNodeModification(disconnectedNodeAcknowledged);
    }

    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    // request manager will ensure that the current is the user that submitted this request
    final AsynchronousWebRequest<?, ComponentValidationResultsEntity> asyncRequest = validationRequestManager.removeRequest(requestType, requestId, user);
    if (asyncRequest == null) {
        throw new ResourceNotFoundException("Could not find request of type " + requestType + " with ID " + requestId);
    }

    if (!asyncRequest.isComplete()) {
        asyncRequest.cancel();
    }

    final ParameterContextValidationRequestEntity requestEntity = createValidationRequestEntity(asyncRequest, contextId, requestType, requestId);
    return generateOkResponse(requestEntity).build();
}
 
Example #5
Source File: AsyncRequestManager.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public AsynchronousWebRequest<R, T> getRequest(final String type, final String id, final NiFiUser user) {
    Objects.requireNonNull(type);
    Objects.requireNonNull(id);
    Objects.requireNonNull(user);

    final String key = getKey(type, id);
    final AsynchronousWebRequest<R, T> request = requests.get(key);
    if (request == null) {
        throw new ResourceNotFoundException("Could not find a Request with identifier " + id);
    }

    if (!request.getUser().equals(user)) {
        throw new IllegalArgumentException("Only the user that submitted the update request can delete it.");
    }

    return request;
}
 
Example #6
Source File: PersistentProvenanceRepository.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
QueryResult queryEvents(final Query query, final NiFiUser user) throws IOException {
    final QuerySubmission submission = submitQuery(query, user);
    final QueryResult result = submission.getResult();
    while (!result.isFinished()) {
        try {
            Thread.sleep(100L);
        } catch (final InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }

    if (result.getError() != null) {
        throw new IOException(result.getError());
    }
    logger.info("{} got {} hits", query, result.getTotalHitCount());
    return result;
}
 
Example #7
Source File: PersistentProvenanceRepository.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Lineage computeLineage(final Collection<String> flowFileUuids, final NiFiUser user, final LineageComputationType computationType, final Long eventId, final Long startTimestamp,
        final Long endTimestamp) throws IOException {
    final AsyncLineageSubmission submission = submitLineageComputation(flowFileUuids, user, computationType, eventId, startTimestamp, endTimestamp);
    final StandardLineageResult result = submission.getResult();
    while (!result.isFinished()) {
        try {
            Thread.sleep(100L);
        } catch (final InterruptedException ie) {
        }
    }

    if (result.getError() != null) {
        throw new IOException(result.getError());
    }

    return new FlowFileLineage(result.getNodes(), result.getEdges());
}
 
Example #8
Source File: LuceneEventIndex.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncLineageSubmission retrieveLineageSubmission(final String lineageIdentifier, final NiFiUser user) {
    final AsyncLineageSubmission submission = lineageSubmissionMap.get(lineageIdentifier);
    final String userId = submission.getSubmitterIdentity();

    if (user == null && userId == null) {
        return submission;
    }

    if (user == null) {
        throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because no user id was provided");
    }

    if (userId == null || userId.equals(user.getIdentity())) {
        return submission;
    }

    throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because " + user.getIdentity() + " is not the user who submitted the request");
}
 
Example #9
Source File: X509AuthenticationProviderTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoProxies() {
    final NiFiAuthenticationToken auth = (NiFiAuthenticationToken) x509AuthenticationProvider.authenticate(getX509Request(buildProxyChain(IDENTITY_1, PROXY_2), PROXY_1));
    final NiFiUser user = ((NiFiUserDetails) auth.getDetails()).getNiFiUser();

    assertNotNull(user);
    assertEquals(IDENTITY_1, user.getIdentity());
    assertFalse(user.isAnonymous());

    assertNotNull(user.getChain());
    assertEquals(PROXY_2, user.getChain().getIdentity());
    assertFalse(user.getChain().isAnonymous());

    assertNotNull(user.getChain().getChain());
    assertEquals(PROXY_1, user.getChain().getChain().getIdentity());
    assertFalse(user.getChain().getChain().isAnonymous());
}
 
Example #10
Source File: LuceneEventIndex.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public QuerySubmission retrieveQuerySubmission(final String queryIdentifier, final NiFiUser user) {
    final QuerySubmission submission = querySubmissionMap.get(queryIdentifier);

    final String userId = submission.getSubmitterIdentity();

    if (user == null && userId == null) {
        return submission;
    }

    if (user == null) {
        throw new AccessDeniedException("Cannot retrieve Provenance Query Submission because no user id was provided");
    }

    if (userId == null || userId.equals(user.getIdentity())) {
        return submission;
    }

    throw new AccessDeniedException("Cannot retrieve Provenance Query Submission because " + user.getIdentity() + " is not the user who submitted the request");
}
 
Example #11
Source File: VolatileProvenanceRepository.java    From nifi with Apache License 2.0 6 votes vote down vote up
public QueryResult queryEvents(final Query query, final NiFiUser user) throws IOException {
    final QuerySubmission submission = submitQuery(query, user);
    final QueryResult result = submission.getResult();
    while (!result.isFinished()) {
        try {
            Thread.sleep(100L);
        } catch (final InterruptedException ie) {
        }
    }

    if (result.getError() != null) {
        throw new IOException(result.getError());
    }

    return result;
}
 
Example #12
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteActions(final Date endDate) {
    // get the user from the request
    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new WebApplicationException(new Throwable("Unable to access details for current user."));
    }

    // create the purge details
    final FlowChangePurgeDetails details = new FlowChangePurgeDetails();
    details.setEndDate(endDate);

    // create a purge action to record that records are being removed
    final FlowChangeAction purgeAction = new FlowChangeAction();
    purgeAction.setUserIdentity(user.getIdentity());
    purgeAction.setOperation(Operation.Purge);
    purgeAction.setTimestamp(new Date());
    purgeAction.setSourceId("Flow Controller");
    purgeAction.setSourceName("History");
    purgeAction.setSourceType(Component.Controller);
    purgeAction.setActionDetails(details);

    // purge corresponding actions
    auditService.purgeActions(endDate, purgeAction);
}
 
Example #13
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 #14
Source File: VolatileProvenanceRepository.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ComputeLineageSubmission retrieveLineageSubmission(String lineageIdentifier, final NiFiUser user) {
    final ComputeLineageSubmission submission = lineageSubmissionMap.get(lineageIdentifier);
    final String userId = submission.getSubmitterIdentity();

    if (user == null && userId == null) {
        return submission;
    }

    if (user == null) {
        throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because no user id was provided in the lineage request.");
    }

    if (userId == null || userId.equals(user.getIdentity())) {
        return submission;
    }

    throw new AccessDeniedException("Cannot retrieve Provenance Lineage Submission because " + user.getIdentity() + " is not the user who submitted the request.");
}
 
Example #15
Source File: ProcessGroupAuditor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an audit record for the creation of a process group.
 *
 * @param processGroup group
 * @param operation operation
 * @param actionDetails details
 * @return action
 */
public Action generateAuditRecord(ProcessGroup processGroup, Operation operation, ActionDetails actionDetails) {
    FlowChangeAction action = null;

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {

        // create the process group action for adding this process group
        action = new FlowChangeAction();
        action.setUserIdentity(user.getIdentity());
        action.setOperation(operation);
        action.setTimestamp(new Date());
        action.setSourceId(processGroup.getIdentifier());
        action.setSourceName(processGroup.getName());
        action.setSourceType(Component.ProcessGroup);

        if (actionDetails != null) {
            action.setActionDetails(actionDetails);
        }
    }

    return action;
}
 
Example #16
Source File: X509AuthenticationProviderTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidAuthenticationException.class)
public void testAnonymousWithOneProxyWhileAnonymousAuthenticationPrevented() {
    final NiFiAuthenticationToken auth = (NiFiAuthenticationToken) x509AuthenticationProvider.authenticate(getX509Request(buildProxyChain(ANONYMOUS), PROXY_1));
    final NiFiUser user = ((NiFiUserDetails) auth.getDetails()).getNiFiUser();

    assertNotNull(user);
    assertEquals(StandardNiFiUser.ANONYMOUS_IDENTITY, user.getIdentity());
    assertTrue(user.isAnonymous());

    assertNotNull(user.getChain());
    assertEquals(PROXY_1, user.getChain().getIdentity());
    assertFalse(user.getChain().isAnonymous());
}
 
Example #17
Source File: DataAuthorizableTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAuthorizationUser() {
    final NiFiUser user = new Builder().identity(IDENTITY_1).build();
    final AuthorizationResult result = testDataAuthorizable.checkAuthorization(testAuthorizer, RequestAction.READ, user, null);

    assertEquals(Result.Approved, result.getResult());
    verify(testAuthorizer, times(1)).authorize(argThat(o -> IDENTITY_1.equals(o.getIdentity())));
}
 
Example #18
Source File: StandardConnectionDAO.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public DownloadableContent getContent(String id, String flowFileUuid, String requestUri) {
    try {
        final NiFiUser user = NiFiUserUtils.getNiFiUser();

        final Connection connection = locateConnection(id);
        final FlowFileQueue queue = connection.getFlowFileQueue();
        final FlowFileRecord flowFile = queue.getFlowFile(flowFileUuid);

        if (flowFile == null) {
            throw new ResourceNotFoundException(String.format("The FlowFile with UUID %s is no longer in the active queue.", flowFileUuid));
        }

        // get the attributes and ensure appropriate access
        final Map<String, String> attributes = flowFile.getAttributes();
        final Authorizable dataAuthorizable = new DataAuthorizable(connection.getSourceAuthorizable());
        dataAuthorizable.authorize(authorizer, RequestAction.READ, user, attributes);

        // get the filename and fall back to the identifier (should never happen)
        String filename = attributes.get(CoreAttributes.FILENAME.key());
        if (filename == null) {
            filename = flowFileUuid;
        }

        // get the mime-type
        final String type = attributes.get(CoreAttributes.MIME_TYPE.key());

        // get the content
        final InputStream content = flowController.getContent(flowFile, user.getIdentity(), requestUri);
        return new DownloadableContent(filename, type, content);
    } catch (final ContentNotFoundException cnfe) {
        throw new ResourceNotFoundException("Unable to find the specified content.");
    } catch (final IOException ioe) {
        logger.error(String.format("Unable to get the content for flowfile (%s) at this time.", flowFileUuid), ioe);
        throw new IllegalStateException("Unable to get the content at this time.");
    }
}
 
Example #19
Source File: StandardEventAccess.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ProcessorStatus getProcessorStatus(final String processorId, final NiFiUser user) {
    final ProcessorNode procNode = flowController.getFlowManager().getProcessorNode(processorId);
    if (procNode == null) {
        return null;
    }

    FlowFileEvent flowFileEvent = flowFileEventRepository.reportTransferEvents(processorId, System.currentTimeMillis());
    if (flowFileEvent == null) {
        flowFileEvent = EmptyFlowFileEvent.INSTANCE;
    }

    final Predicate<Authorizable> authorizer = authorizable -> authorizable.isAuthorized(flowController.getAuthorizer(), RequestAction.READ, user);
    return getProcessorStatus(flowFileEvent, procNode, authorizer);
}
 
Example #20
Source File: VolatileProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
private AsyncLineageSubmission submitLineageComputation(final Collection<String> flowFileUuids, final NiFiUser user, final LineageComputationType computationType, final Long eventId) {
    final String userId = user == null ? null : user.getIdentity();
    final AsyncLineageSubmission result = new AsyncLineageSubmission(computationType, eventId, flowFileUuids, 1, userId);
    lineageSubmissionMap.put(result.getLineageIdentifier(), result);

    final Filter<ProvenanceEventRecord> filter = new Filter<ProvenanceEventRecord>() {
        @Override
        public boolean select(final ProvenanceEventRecord event) {
            if (!isAuthorized(event, user)) {
                return false;
            }

            if (flowFileUuids.contains(event.getFlowFileUuid())) {
                return true;
            }

            for (final String parentId : event.getParentUuids()) {
                if (flowFileUuids.contains(parentId)) {
                    return true;
                }
            }

            for (final String childId : event.getChildUuids()) {
                if (flowFileUuids.contains(childId)) {
                    return true;
                }
            }

            return false;
        }
    };

    queryExecService.submit(new ComputeLineageRunnable(ringBuffer, filter, result));

    return result;
}
 
Example #21
Source File: ComponentNode.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
default void authorize(Authorizer authorizer, RequestAction action, NiFiUser user, Map<String, String> resourceContext) throws AccessDeniedException {
    // 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) {
            restrictedComponentsAuthorizable.authorize(authorizer, RequestAction.WRITE, user, resourceContext);
        }
    }

    // defer to the base authorization check
    ComponentAuthorizable.super.authorize(authorizer, action, user, resourceContext);
}
 
Example #22
Source File: StandardConnection.java    From localization_nifi with Apache License 2.0 5 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.");
    }

    getSourceAuthorizable().authorize(authorizer, action, user, resourceContext);
    getDestinationAuthorizable().authorize(authorizer, action, user, resourceContext);
}
 
Example #23
Source File: AccessResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a single use access token for downloading FlowFile content.
 *
 * @param httpServletRequest the servlet request
 * @return A token (string)
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Path("/download-token")
@ApiOperation(
        value = "Creates a single use access token for downloading FlowFile content.",
        notes = "The token returned is a base64 encoded string. It is valid for a single request up to five minutes from being issued. " +
                "It is used as a query parameter name 'access_token'.",
        response = String.class
)
@ApiResponses(
        value = {
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 409, message = "Unable to create the download token because NiFi is not in the appropriate state. " +
                        "(i.e. may not have any tokens to grant or be configured to support username/password login)"),
                @ApiResponse(code = 500, message = "Unable to create download token because an unexpected error occurred.")
        }
)
public Response createDownloadToken(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Download tokens are only issued over HTTPS.");
    }

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new AccessDeniedException("No user authenticated in the request.");
    }

    final OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(user.getIdentity());

    // generate otp for response
    final String token = otpService.generateDownloadToken(authenticationToken);

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "download-token"));
    return generateCreatedResponse(uri, token).build();
}
 
Example #24
Source File: RelationshipAuditor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the audit records for the specified connection.
 *
 * @param connection connection
 * @param operation operation
 * @param actionDetails details
 * @return action
 */
public Action generateAuditRecordForConnection(Connection connection, Operation operation, ActionDetails actionDetails) {
    FlowChangeAction action = null;

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {
        // determine the source details
        final String connectionId = connection.getIdentifier();

        String connectionName = connection.getName();
        if (StringUtils.isBlank(connectionName)) {
            Collection<String> relationshipNames = new HashSet<>(connection.getRelationships().size());
            for (final Relationship relationship : connection.getRelationships()) {
                relationshipNames.add(relationship.getName());
            }
            connectionName = StringUtils.join(relationshipNames, ", ");
        }

        // go through each relationship added
        Date actionTimestamp = new Date();

        // create a new relationship action
        action = new FlowChangeAction();
        action.setUserIdentity(user.getIdentity());
        action.setOperation(operation);
        action.setTimestamp(actionTimestamp);
        action.setSourceId(connectionId);
        action.setSourceName(connectionName);
        action.setSourceType(Component.Connection);

        if (actionDetails != null) {
            action.setActionDetails(actionDetails);
        }
    }

    return action;
}
 
Example #25
Source File: VolatileProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProvenanceEventRecord> getEvents(final long firstRecordId, final int maxRecords, final NiFiUser user) throws IOException {
    return ringBuffer.getSelectedElements(new Filter<ProvenanceEventRecord>() {
        @Override
        public boolean select(final ProvenanceEventRecord value) {
            if (!isAuthorized(value, user)) {
                return false;
            }

            return value.getEventId() >= firstRecordId;
        }
    }, maxRecords);
}
 
Example #26
Source File: ControllerServiceAuditor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates an audit record for the creation of a controller service.
 *
 * @param controllerService service
 * @param operation operation
 * @param actionDetails details
 * @return action
 */
private Action generateAuditRecord(ControllerServiceNode controllerService, Operation operation, ActionDetails actionDetails) {
    FlowChangeAction action = null;

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {
        // create the controller service details
        FlowChangeExtensionDetails serviceDetails = new FlowChangeExtensionDetails();
        serviceDetails.setType(controllerService.getComponentType());

        // create the controller service action for adding this controller service
        action = new FlowChangeAction();
        action.setUserIdentity(user.getIdentity());
        action.setOperation(operation);
        action.setTimestamp(new Date());
        action.setSourceId(controllerService.getIdentifier());
        action.setSourceName(controllerService.getName());
        action.setSourceType(Component.ControllerService);
        action.setComponentDetails(serviceDetails);

        if (actionDetails != null) {
            action.setActionDetails(actionDetails);
        }
    }

    return action;
}
 
Example #27
Source File: ITestPersistentProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
private NiFiUser createUser() {
    return new NiFiUser() {
        @Override
        public String getIdentity() {
            return "unit-test";
        }

        @Override
        public Set<String> getGroups() {
            return Collections.EMPTY_SET;
        }

        @Override
        public NiFiUser getChain() {
            return null;
        }

        @Override
        public boolean isAnonymous() {
            return false;
        }

        @Override
        public String getClientAddress() {
            return null;
        }

    };
}
 
Example #28
Source File: PersistentProvenanceRepository.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ProvenanceEventRecord getEvent(final long id, final NiFiUser user) throws IOException {
    final ProvenanceEventRecord event = getEvent(id);
    if (event == null) {
        return null;
    }

    authorize(event, user);
    return event;
}
 
Example #29
Source File: LuceneEventIndex.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ComputeLineageSubmission submitLineageComputation(final Collection<String> flowFileUuids, final NiFiUser user, final EventAuthorizer eventAuthorizer,
    final LineageComputationType computationType, final Long eventId, final long startTimestamp, final long endTimestamp) {

    final List<File> indexDirs = directoryManager.getDirectories(startTimestamp, endTimestamp);
    final AsyncLineageSubmission submission = new AsyncLineageSubmission(computationType, eventId, flowFileUuids, indexDirs.size(), user.getIdentity());
    lineageSubmissionMap.put(submission.getLineageIdentifier(), submission);

    final BooleanQuery lineageQuery = buildLineageQuery(flowFileUuids);
    final List<File> indexDirectories = directoryManager.getDirectories(startTimestamp, endTimestamp);
    if (indexDirectories.isEmpty()) {
        submission.getResult().update(Collections.emptyList(), 0L);
    } else {
        Collections.sort(indexDirectories, DirectoryUtils.OLDEST_INDEX_FIRST);

        for (final File indexDir : indexDirectories) {
            queryExecutor.submit(new QueryTask(lineageQuery, submission.getResult(), MAX_LINEAGE_NODES, indexManager, indexDir,
                eventStore, eventAuthorizer, EventTransformer.PLACEHOLDER_TRANSFORMER));
        }
    }

    // Some computations will complete very quickly. In this case, we don't want to wait
    // for the client to submit a second query to obtain the result. Instead, we want to just
    // wait some short period of time for the computation to complete before returning the submission.
    try {
        submission.getResult().awaitCompletion(500, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException ie) {
        Thread.currentThread().interrupt();
    }

    return submission;
}
 
Example #30
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);
}