org.apache.nifi.authorization.resource.Authorizable Java Examples

The following examples show how to use org.apache.nifi.authorization.resource.Authorizable. 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: UserEventAuthorizer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isAuthorized(final ProvenanceEventRecord event) {
    if (authorizer == null || user == null) {
        return true;
    }

    final Authorizable eventAuthorizable;
    try {
        if (event.isRemotePortType()) {
            eventAuthorizable = resourceFactory.createRemoteDataAuthorizable(event.getComponentId());
        } else {
            eventAuthorizable = resourceFactory.createLocalDataAuthorizable(event.getComponentId());
        }
    } catch (final ResourceNotFoundException rnfe) {
        return false;
    }

    final AuthorizationResult result = eventAuthorizable.checkAuthorization(authorizer, RequestAction.READ, user, event.getAttributes());
    return Result.Approved.equals(result.getResult());
}
 
Example #2
Source File: ControllerFacade.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes access to replay a specified provenance event.
 *
 * @param event event
 */
private AuthorizationResult checkAuthorizationForReplay(final ProvenanceEventRecord event) {
    // if the connection id isn't specified, then the replay wouldn't be available anyways and we have nothing to authorize against so deny it`
    if (event.getSourceQueueIdentifier() == null) {
        return AuthorizationResult.denied("The connection id in the provenance event is unknown.");
    }

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final Authorizable dataAuthorizable;
    if (event.isRemotePortType()) {
        dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId());
    } else {
        dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId());
    }

    final Map<String, String> eventAttributes = event.getAttributes();

    // ensure we can read the data
    final AuthorizationResult result = dataAuthorizable.checkAuthorization(authorizer, RequestAction.READ, user, eventAttributes);
    if (!Result.Approved.equals(result.getResult())) {
        return result;
    }

    // ensure we can write the data
    return dataAuthorizable.checkAuthorization(authorizer, RequestAction.WRITE, user, eventAttributes);
}
 
Example #3
Source File: StandardControllerServiceNode.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Authorizable getParentAuthorizable() {
    final ProcessGroup processGroup = getProcessGroup();
    if (processGroup == null) {
        return new Authorizable() {
            @Override
            public Authorizable getParentAuthorizable() {
                return null;
            }

            @Override
            public Resource getResource() {
                return ResourceFactory.getControllerResource();
            }
        };
    } else {
        return processGroup;
    }
}
 
Example #4
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public UserEntity updateUser(final Revision revision, final UserDTO userDTO) {
    final Authorizable usersAuthorizable = authorizableLookup.getTenant();
    final Set<Group> groups = userGroupDAO.getUserGroupsForUser(userDTO.getId());
    final Set<AccessPolicy> policies = userGroupDAO.getAccessPoliciesForUser(userDTO.getId());
    final RevisionUpdate<UserDTO> snapshot = updateComponent(revision,
            usersAuthorizable,
            () -> userDAO.updateUser(userDTO),
            user -> {
                final Set<TenantEntity> tenantEntities = groups.stream().map(g -> g.getIdentifier()).map(mapUserGroupIdToTenantEntity()).collect(Collectors.toSet());
                final Set<AccessPolicySummaryEntity> policyEntities = policies.stream().map(ap -> createAccessPolicySummaryEntity(ap)).collect(Collectors.toSet());
                return dtoFactory.createUserDto(user, tenantEntities, policyEntities);
            });

    final PermissionsDTO permissions = dtoFactory.createPermissionsDto(usersAuthorizable);
    return entityFactory.createUserEntity(snapshot.getComponent(), dtoFactory.createRevisionDTO(snapshot.getLastModification()), permissions);
}
 
Example #5
Source File: AuthorizeParameterReference.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static void authorizeParameterReferences(final Map<String, String> proposedProperties, final Authorizer authorizer, final Authorizable parameterContextAuthorizable, final NiFiUser user) {
    if (proposedProperties == null || parameterContextAuthorizable == null) {
        return;
    }

    final ParameterParser parameterParser = new ExpressionLanguageAgnosticParameterParser();

    boolean referencesParameter = false;
    for (final String proposedPropertyValue : proposedProperties.values()) {
        // Check if any Parameter is referenced. If so, user must have READ policy on the Parameter Context
        ParameterTokenList tokenList = parameterParser.parseTokens(proposedPropertyValue);
        if (!tokenList.toReferenceList().isEmpty()) {
            referencesParameter = true;
            break;
        }
    }

    if (referencesParameter) {
        parameterContextAuthorizable.authorize(authorizer, RequestAction.READ, user);
    }
}
 
Example #6
Source File: StandardAuthorizableLookup.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public RootGroupPortAuthorizable getRootGroupInputPort(String id) {
    final Port inputPort = inputPortDAO.getPort(id);

    if (!(inputPort instanceof RootGroupPort)) {
        throw new IllegalArgumentException(String.format("The specified id '%s' does not represent an input port in the root group.", id));
    }

    final DataTransferAuthorizable baseAuthorizable = new DataTransferAuthorizable(inputPort);
    return new RootGroupPortAuthorizable() {
        @Override
        public Authorizable getAuthorizable() {
            return baseAuthorizable;
        }

        @Override
        public AuthorizationResult checkAuthorization(NiFiUser user) {
            // perform the authorization of the user by using the underlying component, ensures consistent authorization with raw s2s
            final PortAuthorizationResult authorizationResult = ((RootGroupPort) inputPort).checkUserAuthorization(user);
            if (authorizationResult.isAuthorized()) {
                return AuthorizationResult.approved();
            } else {
                return AuthorizationResult.denied(authorizationResult.getExplanation());
            }
        }
    };
}
 
Example #7
Source File: PersistentProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(final ProvenanceEventRecord event, final NiFiUser user) {
    if (authorizer == null || user == null) {
        return true;
    }

    final Authorizable eventAuthorizable;
    try {
        eventAuthorizable = resourceFactory.createProvenanceDataAuthorizable(event.getComponentId());
    } catch (final ResourceNotFoundException rnfe) {
        return false;
    }

    final AuthorizationResult result = eventAuthorizable.checkAuthorization(authorizer, RequestAction.READ, user);
    return Result.Approved.equals(result.getResult());
}
 
Example #8
Source File: WriteAheadProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void authorize(final ProvenanceEventRecord event, final NiFiUser user) {
    if (authorizer == null || user == null) {
        return;
    }

    final Authorizable eventAuthorizable = resourceFactory.createProvenanceDataAuthorizable(event.getComponentId());
    eventAuthorizable.authorize(authorizer, RequestAction.READ, user);
}
 
Example #9
Source File: VolatileProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void authorize(final ProvenanceEventRecord event, final NiFiUser user) {
    if (authorizer == null || user == null) {
        return;
    }

    final Authorizable eventAuthorizable = resourceFactory.createProvenanceDataAuthorizable(event.getComponentId());
    eventAuthorizable.authorize(authorizer, RequestAction.READ, user);
}
 
Example #10
Source File: ControllerResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to the flow.
 */
private void authorizeController(final RequestAction action) {
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable controller = lookup.getController();
        controller.authorize(authorizer, action, NiFiUserUtils.getNiFiUser());
    });
}
 
Example #11
Source File: FlowResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes access to the flow.
 */
private void authorizeFlow() {
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable flow = lookup.getFlow();
        flow.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });
}
 
Example #12
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 #13
Source File: StandardConnection.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Authorizable getDestinationAuthorizable() {
    final Connectable destinationConnectable = getDestination();
    final Authorizable destinationAuthorizable;

    // if the destination is a remote group port, authorize according to the RPG
    if (destinationConnectable instanceof RemoteGroupPort) {
        destinationAuthorizable = ((RemoteGroupPort) destinationConnectable).getRemoteProcessGroup();
    } else {
        destinationAuthorizable = destinationConnectable;
    }

    return destinationAuthorizable;
}
 
Example #14
Source File: ApplicationResource.java    From 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 boolean authorizeParameterReferences) {

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

    // authorize each component in the specified snippet
    snippet.getSelectedProcessGroups().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, authorizeParameterReferences);
    });
    snippet.getSelectedRemoteProcessGroups().forEach(authorize);
    snippet.getSelectedProcessors().forEach(processorAuthorizable -> {
        // authorize the processor
        authorize.accept(processorAuthorizable.getAuthorizable());

        // authorize any referenced services if necessary
        if (authorizeReferencedServices) {
            AuthorizeControllerServiceReference.authorizeControllerServiceReferences(processorAuthorizable, authorizer, lookup, authorizeTransitiveServices);
        }

        // authorize any parameter usage
        if (authorizeParameterReferences) {
            AuthorizeParameterReference.authorizeParameterReferences(processorAuthorizable, authorizer, processorAuthorizable.getParameterContext(), user);
        }
    });
    snippet.getSelectedInputPorts().forEach(authorize);
    snippet.getSelectedOutputPorts().forEach(authorize);
    snippet.getSelectedConnections().forEach(connAuth -> authorize.accept(connAuth.getAuthorizable()));
    snippet.getSelectedFunnels().forEach(authorize);
    snippet.getSelectedLabels().forEach(authorize);
}
 
Example #15
Source File: AuthorizeControllerServiceReference.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the proposed properties for the specified authorizable.
 *
 * @param proposedProperties proposed properties
 * @param authorizable authorizable that may reference a controller service
 * @param authorizer authorizer
 * @param lookup lookup
 */
public static void authorizeControllerServiceReferences(final Map<String, String> proposedProperties, final ConfigurableComponentAuthorizable authorizable,
                                                        final Authorizer authorizer, final AuthorizableLookup lookup) {

    // only attempt to authorize if properties are changing
    if (proposedProperties != null) {
        final NiFiUser user = NiFiUserUtils.getNiFiUser();

        for (final Map.Entry<String, String> entry : proposedProperties.entrySet()) {
            final String propertyName = entry.getKey();
            final PropertyDescriptor propertyDescriptor = authorizable.getPropertyDescriptor(propertyName);

            // if this descriptor identifies a controller service
            if (propertyDescriptor.getControllerServiceDefinition() != null) {
                final String currentValue = authorizable.getValue(propertyDescriptor);
                final String proposedValue = entry.getValue();

                // if the value is changing
                if (!Objects.equals(currentValue, proposedValue)) {
                    // ensure access to the old service
                    if (currentValue != null) {
                        try {
                            final Authorizable currentServiceAuthorizable = lookup.getControllerService(currentValue).getAuthorizable();
                            currentServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                        } catch (ResourceNotFoundException e) {
                            // ignore if the resource is not found, if currentValue was previously deleted, it should not stop assignment of proposedValue
                        }
                    }

                    // ensure access to the new service
                    if (proposedValue != null) {
                        final Authorizable newServiceAuthorizable = lookup.getControllerService(proposedValue).getAuthorizable();
                        newServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                    }
                }
            }
        }
    }
}
 
Example #16
Source File: ControllerFacade.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Authorizable getDataAuthorizable(final ProvenanceEventRecord event) {
    if (event.isRemotePortType()) {
        return flowController.getProvenanceAuthorizableFactory().createRemoteDataAuthorizable(event.getComponentId());
    } else {
        return flowController.getProvenanceAuthorizableFactory().createLocalDataAuthorizable(event.getComponentId());
    }
}
 
Example #17
Source File: StandardConnection.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Authorizable getSourceAuthorizable() {
    final Connectable sourceConnectable = getSource();
    final Authorizable sourceAuthorizable;

    // if the source is a remote group port, authorize according to the RPG
    if (sourceConnectable instanceof RemoteGroupPort) {
        sourceAuthorizable = ((RemoteGroupPort) sourceConnectable).getRemoteProcessGroup();
    } else {
        sourceAuthorizable = sourceConnectable;
    }

    return sourceAuthorizable;
}
 
Example #18
Source File: ProcessorResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Clears the state for a processor.
 *
 * @param httpServletRequest servlet request
 * @param id                 The id of the processor
 * @return a componentStateEntity
 * @throws InterruptedException if interrupted
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/state/clear-requests")
@ApiOperation(
        value = "Clears the state for a processor",
        response = ComponentStateDTO.class,
        authorizations = {
                @Authorization(value = "Write - /processors/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response clearState(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The processor id.",
                required = true
        )
        @PathParam("id") final String id) throws InterruptedException {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST);
    }

    final ProcessorEntity requestProcessorEntity = new ProcessorEntity();
    requestProcessorEntity.setId(id);

    return withWriteLock(
            serviceFacade,
            requestProcessorEntity,
            lookup -> {
                final Authorizable processor = lookup.getProcessor(id).getAuthorizable();
                processor.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyCanClearProcessorState(id),
            (processorEntity) -> {
                // get the component state
                serviceFacade.clearProcessorState(processorEntity.getId());

                // generate the response entity
                final ComponentStateEntity entity = new ComponentStateEntity();

                // generate the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #19
Source File: StandardAuthorizableLookup.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Authorizable getOutputPort(final String id) {
    return outputPortDAO.getPort(id);
}
 
Example #20
Source File: ProcessorResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the state for a processor.
 *
 * @param id The id of the processor
 * @return a componentStateEntity
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/state")
@ApiOperation(
        value = "Gets the state for a processor",
        response = ComponentStateDTO.class,
        authorizations = {
                @Authorization(value = "Write - /processors/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response getState(
        @ApiParam(
                value = "The processor id.",
                required = true
        )
        @PathParam("id") final String id) throws InterruptedException {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable processor = lookup.getProcessor(id).getAuthorizable();
        processor.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
    });

    // get the component state
    final ComponentStateDTO state = serviceFacade.getProcessorState(id);

    // generate the response entity
    final ComponentStateEntity entity = new ComponentStateEntity();
    entity.setComponentState(state);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #21
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the specified process group.
 *
 * @param httpServletRequest request
 * @param id                 The id of the process group.
 * @param requestProcessGroupEntity A processGroupEntity.
 * @return A processGroupEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates a process group",
        response = ProcessGroupEntity.class,
        authorizations = {
                @Authorization(value = "Write - /process-groups/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response updateProcessGroup(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The process group configuration details.",
                required = true
        ) final ProcessGroupEntity requestProcessGroupEntity) {

    if (requestProcessGroupEntity == null || requestProcessGroupEntity.getComponent() == null) {
        throw new IllegalArgumentException("Process group details must be specified.");
    }

    if (requestProcessGroupEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the same id is being used
    final ProcessGroupDTO requestProcessGroupDTO = requestProcessGroupEntity.getComponent();
    if (!id.equals(requestProcessGroupDTO.getId())) {
        throw new IllegalArgumentException(String.format("The process group id (%s) in the request body does "
                + "not equal the process group id of the requested resource (%s).", requestProcessGroupDTO.getId(), id));
    }

    final PositionDTO proposedPosition = requestProcessGroupDTO.getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestProcessGroupEntity);
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestProcessGroupEntity, id);
    return withWriteLock(
            serviceFacade,
            requestProcessGroupEntity,
            requestRevision,
            lookup -> {
                Authorizable authorizable = lookup.getProcessGroup(id).getAuthorizable();
                authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            (revision, processGroupEntity) -> {
                // update the process group
                final ProcessGroupEntity entity = serviceFacade.updateProcessGroup(revision, processGroupEntity.getComponent());
                populateRemainingProcessGroupEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #22
Source File: AccessPolicyResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the specified access policy.
 *
 * @param id The id of the access policy to retrieve
 * @return An accessPolicyEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Gets an access policy",
        response = AccessPolicyEntity.class,
        authorizations = {
                @Authorization(value = "Read - /policies/{resource}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response getAccessPolicy(
        @ApiParam(
                value = "The access policy id.",
                required = true
        )
        @PathParam("id") final String id) {

    // ensure we're running with a configurable authorizer
    if (!(authorizer instanceof AbstractPolicyBasedAuthorizer)) {
        throw new IllegalStateException(AccessPolicyDAO.MSG_NON_ABSTRACT_POLICY_BASED_AUTHORIZER);
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        Authorizable authorizable = lookup.getAccessPolicyById(id);
        authorizable.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the access policy
    final AccessPolicyEntity entity = serviceFacade.getAccessPolicy(id);
    populateRemainingAccessPolicyEntityContent(entity);

    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #23
Source File: StandardRemoteProcessGroup.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Authorizable getParentAuthorizable() {
    return getProcessGroup();
}
 
Example #24
Source File: StandardAuthorizableLookup.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Authorizable getCounters() {
    return COUNTERS_AUTHORIZABLE;
}
 
Example #25
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves all the of remote process groups in this NiFi.
 *
 * @return A remoteProcessGroupEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/remote-process-groups")
@ApiOperation(
        value = "Gets all remote process groups",
        response = RemoteProcessGroupsEntity.class,
        authorizations = {
                @Authorization(value = "Read - /process-groups/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response getRemoteProcessGroups(
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") final String groupId) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get all the remote process groups
    final Set<RemoteProcessGroupEntity> remoteProcessGroups = serviceFacade.getRemoteProcessGroups(groupId);

    // prune response as necessary
    for (RemoteProcessGroupEntity remoteProcessGroupEntity : remoteProcessGroups) {
        if (remoteProcessGroupEntity.getComponent() != null) {
            remoteProcessGroupEntity.getComponent().setContents(null);
        }
    }

    // create the response entity
    final RemoteProcessGroupsEntity entity = new RemoteProcessGroupsEntity();
    entity.setRemoteProcessGroups(remoteProcessGroupResource.populateRemainingRemoteProcessGroupEntitiesContent(remoteProcessGroups));

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #26
Source File: TenantsResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new user group.
 *
 * @param httpServletRequest request
 * @param requestUserGroupEntity    An userGroupEntity.
 * @return An userGroupEntity.
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("user-groups")
@ApiOperation(
        value = "Creates a user group",
        notes = NON_GUARANTEED_ENDPOINT,
        response = UserGroupEntity.class,
        authorizations = {
                @Authorization(value = "Write - /tenants")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response createUserGroup(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The user group configuration details.",
                required = true
        ) final UserGroupEntity requestUserGroupEntity) {

    // ensure we're running with a configurable authorizer
    if (!AuthorizerCapabilityDetection.isConfigurableUserGroupProvider(authorizer)) {
        throw new IllegalStateException(AccessPolicyDAO.MSG_NON_CONFIGURABLE_USERS);
    }

    if (requestUserGroupEntity == null || requestUserGroupEntity.getComponent() == null) {
        throw new IllegalArgumentException("User group details must be specified.");
    }

    if (requestUserGroupEntity.getRevision() == null || (requestUserGroupEntity.getRevision().getVersion() == null || requestUserGroupEntity.getRevision().getVersion() != 0)) {
        throw new IllegalArgumentException("A revision of 0 must be specified when creating a new User Group.");
    }

    if (requestUserGroupEntity.getComponent().getId() != null) {
        throw new IllegalArgumentException("User group ID cannot be specified.");
    }

    if (StringUtils.isBlank(requestUserGroupEntity.getComponent().getIdentity())) {
        throw new IllegalArgumentException("User group identity must be specified.");
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST, requestUserGroupEntity);
    } else if (isDisconnectedFromCluster()) {
        verifyDisconnectedNodeModification(requestUserGroupEntity.isDisconnectedNodeAcknowledged());
    }

    return withWriteLock(
            serviceFacade,
            requestUserGroupEntity,
            lookup -> {
                final Authorizable tenants = lookup.getTenant();
                tenants.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            userGroupEntity -> {
                // set the user group id as appropriate
                userGroupEntity.getComponent().setId(generateUuid());

                // get revision from the config
                final RevisionDTO revisionDTO = userGroupEntity.getRevision();
                Revision revision = new Revision(revisionDTO.getVersion(), revisionDTO.getClientId(), userGroupEntity.getComponent().getId());

                // create the user group and generate the json
                final UserGroupEntity entity = serviceFacade.createUserGroup(revision, userGroupEntity.getComponent());
                populateRemainingUserGroupEntityContent(entity);

                // build the response
                return generateCreatedResponse(URI.create(entity.getUri()), entity).build();
            }
    );
}
 
Example #27
Source File: ControllerFacade.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Authorizable getParentAuthorizable() {
    return flowController.getParentAuthorizable();
}
 
Example #28
Source File: FunnelResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new Funnel.
 *
 * @param httpServletRequest request
 * @param id                 The id of the funnel to update.
 * @param requestFunnelEntity       A funnelEntity.
 * @return A funnelEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates a funnel",
        response = FunnelEntity.class,
        authorizations = {
                @Authorization(value = "Write - /funnels/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response updateFunnel(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The funnel id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The funnel configuration details.",
                required = true
        ) final FunnelEntity requestFunnelEntity) {

    if (requestFunnelEntity == null || requestFunnelEntity.getComponent() == null) {
        throw new IllegalArgumentException("Funnel details must be specified.");
    }

    if (requestFunnelEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the ids are the same
    final FunnelDTO requestFunnelDTO = requestFunnelEntity.getComponent();
    if (!id.equals(requestFunnelDTO.getId())) {
        throw new IllegalArgumentException(String.format("The funnel id (%s) in the request body does not equal the "
                + "funnel id of the requested resource (%s).", requestFunnelDTO.getId(), id));
    }

    final PositionDTO proposedPosition = requestFunnelDTO.getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestFunnelEntity);
    }

    // Extract the revision
    final Revision requestRevision = getRevision(requestFunnelEntity, id);
    return withWriteLock(
            serviceFacade,
            requestFunnelEntity,
            requestRevision,
            lookup -> {
                Authorizable authorizable = lookup.getFunnel(id);
                authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            (revision, funnelEntity) -> {
                // update the funnel
                final FunnelEntity entity = serviceFacade.updateFunnel(revision, funnelEntity.getComponent());
                populateRemainingFunnelEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #29
Source File: FunnelResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the specified funnel.
 *
 * @param id The id of the funnel to retrieve
 * @return A funnelEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Gets a funnel",
        response = FunnelEntity.class,
        authorizations = {
                @Authorization(value = "Read - /funnels/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response getFunnel(
        @ApiParam(
                value = "The funnel id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable funnel = lookup.getFunnel(id);
        funnel.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the funnel
    final FunnelEntity entity = serviceFacade.getFunnel(id);
    populateRemainingFunnelEntityContent(entity);

    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #30
Source File: InputPortResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the operational status for the specified input port with the specified values.
 *
 * @param httpServletRequest request
 * @param id                 The id of the port to update.
 * @param requestRunStatus    A portRunStatusEntity.
 * @return A portEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/run-status")
@ApiOperation(
        value = "Updates run status of an input-port",
        response = ProcessorEntity.class,
        authorizations = {
                @Authorization(value = "Write - /input-ports/{uuid} or /operation/input-ports/{uuid}")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response updateRunStatus(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The port id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The port run status.",
                required = true
        ) final PortRunStatusEntity requestRunStatus) {

    if (requestRunStatus == null) {
        throw new IllegalArgumentException("Port run status must be specified.");
    }

    if (requestRunStatus.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    requestRunStatus.validateState();

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestRunStatus);
    } else if (isDisconnectedFromCluster()) {
        verifyDisconnectedNodeModification(requestRunStatus.isDisconnectedNodeAcknowledged());
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestRunStatus.getRevision(), id);
    return withWriteLock(
            serviceFacade,
            requestRunStatus,
            requestRevision,
            lookup -> {
                final NiFiUser user = NiFiUserUtils.getNiFiUser();

                final Authorizable authorizable = lookup.getInputPort(id);
                OperationAuthorizable.authorizeOperation(authorizable, authorizer, user);
            },
            () -> serviceFacade.verifyUpdateInputPort(createDTOWithDesiredRunStatus(id, requestRunStatus.getState())),
            (revision, runStatusEntity) -> {
                // update the input port
                final PortEntity entity = serviceFacade.updateInputPort(revision, createDTOWithDesiredRunStatus(id, runStatusEntity.getState()));
                populateRemainingInputPortEntityContent(entity);

                return generateOkResponse(entity).build();
            }
    );
}