Ejemplo n.º 1
0
  /**
   * Generates an audit record for the creation of a processor.
   *
   * @param processor processor
   * @param operation operation
   * @param actionDetails details
   * @return action
   */
  public Action generateAuditRecord(
      ProcessorNode processor, 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 processor details
      FlowChangeExtensionDetails processorDetails = new FlowChangeExtensionDetails();
      processorDetails.setType(processor.getProcessor().getClass().getSimpleName());

      // create the processor action for adding this processor
      action = new FlowChangeAction();
      action.setUserIdentity(user.getIdentity());
      action.setUserName(user.getUserName());
      action.setOperation(operation);
      action.setTimestamp(new Date());
      action.setSourceId(processor.getIdentifier());
      action.setSourceName(processor.getName());
      action.setSourceType(Component.Processor);
      action.setComponentDetails(processorDetails);

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

    return action;
  }
Ejemplo n.º 2
0
  private void authorizeSystem() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

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

    final AuthorizationRequest request =
        new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getSystemResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
      final String message =
          StringUtils.isNotBlank(result.getExplanation())
              ? result.getExplanation()
              : "Access is denied";
      throw new AccessDeniedException(message);
    }
  }
Ejemplo n.º 3
0
  /**
   * Retrieves the specified access policy.
   *
   * @return An accessPolicyEntity.
   */
  @GET
  @Consumes(MediaType.WILDCARD)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{action}/{resource: .+}")
  // TODO - @PreAuthorize("hasAnyRole('ROLE_MONITOR', 'ROLE_DFM', 'ROLE_ADMIN')")
  @ApiOperation(
      value = "Gets an access policy",
      response = AccessPolicyEntity.class,
      authorizations = {
        @Authorization(value = "Read Only", type = "ROLE_MONITOR"),
        @Authorization(value = "Data Flow Manager", type = "ROLE_DFM"),
        @Authorization(value = "Administrator", type = "ROLE_ADMIN")
      })
  @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 getAccessPolicyForResource(
      @ApiParam(value = "The request action.", allowableValues = "read, write", required = true)
          @PathParam("action")
          final String action,
      @ApiParam(value = "The resource of the policy.", required = true) @PathParam("resource")
          String rawResource) {

    // parse the action and resource type
    final RequestAction requestAction = RequestAction.valueOfValue(action);
    final String resource = "/" + rawResource;

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

    // authorize access
    serviceFacade.authorizeAccess(
        lookup -> {
          final Authorizable accessPolicy = lookup.getAccessPolicyByResource(resource);
          accessPolicy.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
        });

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

    return clusterContext(generateOkResponse(entity)).build();
  }
Ejemplo n.º 4
0
  /**
   * Removes the specified template.
   *
   * @param httpServletRequest request
   * @param id The id of the template to remove.
   * @return A templateEntity.
   */
  @DELETE
  @Consumes(MediaType.WILDCARD)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{id}")
  @ApiOperation(
      value = "Deletes a template",
      response = TemplateEntity.class,
      authorizations = {@Authorization(value = "Write - /templates/{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 removeTemplate(
      @Context final HttpServletRequest httpServletRequest,
      @ApiParam(value = "The template id.", required = true) @PathParam("id") final String id) {

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

    final TemplateEntity requestTemplateEntity = new TemplateEntity();
    requestTemplateEntity.setId(id);

    return withWriteLock(
        serviceFacade,
        requestTemplateEntity,
        lookup -> {
          final Authorizable template = lookup.getTemplate(id);
          template.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        },
        null,
        (templateEntity) -> {
          // delete the specified template
          serviceFacade.deleteTemplate(templateEntity.getId());

          // build the response entity
          final TemplateEntity entity = new TemplateEntity();

          return clusterContext(generateOkResponse(entity)).build();
        });
  }
Ejemplo n.º 5
0
 /**
  * Executes an action through the service facade using the specified revision.
  *
  * @param serviceFacade service facade
  * @param revisions revisions
  * @param authorizer authorizer
  * @param verifier verifier
  * @param action executor
  * @return the response
  */
 protected Response withWriteLock(
     final NiFiServiceFacade serviceFacade,
     final Set<Revision> revisions,
     final AuthorizeAccess authorizer,
     final Runnable verifier,
     final Supplier<Response> action) {
   final NiFiUser user = NiFiUserUtils.getNiFiUser();
   return withWriteLock(
       serviceFacade,
       authorizer,
       verifier,
       action,
       () -> serviceFacade.claimRevisions(revisions, user),
       () -> serviceFacade.cancelRevisions(revisions),
       () -> serviceFacade.releaseRevisionClaims(revisions, user));
 }
Ejemplo n.º 6
0
  /**
   * Retrieves the specified output port.
   *
   * @param id The id of the output port to retrieve
   * @return A outputPortEntity.
   */
  @GET
  @Consumes(MediaType.WILDCARD)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{id}")
  @ApiOperation(
      value = "Gets an output port",
      response = PortEntity.class,
      authorizations = {@Authorization(value = "Read - /output-ports/{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 getOutputPort(
      @ApiParam(value = "The output port id.", required = true) @PathParam("id") final String id) {

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

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

    // get the port
    final PortEntity entity = serviceFacade.getOutputPort(id);
    populateRemainingOutputPortEntityContent(entity);

    return clusterContext(generateOkResponse(entity)).build();
  }
Ejemplo n.º 7
0
  /**
   * Retrieves the specified template.
   *
   * @param id The id of the template to retrieve
   * @return A templateEntity.
   */
  @GET
  @Consumes(MediaType.WILDCARD)
  @Produces(MediaType.APPLICATION_XML)
  @Path("{id}/download")
  @ApiOperation(
      value = "Exports a template",
      response = TemplateDTO.class,
      authorizations = {@Authorization(value = "Read - /templates/{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 exportTemplate(
      @ApiParam(value = "The template id.", required = true) @PathParam("id") final String id) {

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

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

    // get the template
    final TemplateDTO template = serviceFacade.exportTemplate(id);

    // prune the template id
    template.setId(null);

    // determine the name of the attachement - possible issues with spaces in file names
    String attachmentName = template.getName();
    if (StringUtils.isBlank(attachmentName)) {
      attachmentName = "template";
    } else {
      attachmentName = attachmentName.replaceAll("\\s", "_");
    }

    // generate the response
    /*
     * Here instead of relying on default JAXB marshalling we are simply
     * serializing template to String (formatted, indented etc) and sending
     * it as part of the response.
     */
    String serializedTemplate =
        new String(TemplateSerializer.serialize(template), StandardCharsets.UTF_8);
    return generateOkResponse(serializedTemplate)
        .header(
            "Content-Disposition", String.format("attachment; filename=\"%s.xml\"", attachmentName))
        .build();
  }
Ejemplo n.º 8
0
  /**
   * Audits the configuration of a single processor.
   *
   * @param proceedingJoinPoint join point
   * @param processorDTO dto
   * @param processorDAO dao
   * @return node
   * @throws Throwable ex
   */
  @Around(
      "within(org.apache.nifi.web.dao.ProcessorDAO+) && "
          + "execution(org.apache.nifi.controller.ProcessorNode updateProcessor(org.apache.nifi.web.api.dto.ProcessorDTO)) && "
          + "args(processorDTO) && "
          + "target(processorDAO)")
  public ProcessorNode updateProcessorAdvice(
      ProceedingJoinPoint proceedingJoinPoint, ProcessorDTO processorDTO, ProcessorDAO processorDAO)
      throws Throwable {
    // determine the initial values for each property/setting thats changing
    ProcessorNode processor = processorDAO.getProcessor(processorDTO.getId());
    final Map<String, String> values = extractConfiguredPropertyValues(processor, processorDTO);
    final ScheduledState scheduledState = processor.getScheduledState();

    // update the processor state
    final ProcessorNode updatedProcessor = (ProcessorNode) proceedingJoinPoint.proceed();

    // if no exceptions were thrown, add the processor action...
    // get the updated verbose state
    processor = processorDAO.getProcessor(updatedProcessor.getIdentifier());

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

    // ensure the user was found
    if (user != null) {
      // determine the updated values
      Map<String, String> updatedValues = extractConfiguredPropertyValues(processor, processorDTO);

      // create the processor details
      FlowChangeExtensionDetails processorDetails = new FlowChangeExtensionDetails();
      processorDetails.setType(processor.getProcessor().getClass().getSimpleName());

      // create a processor action
      Date actionTimestamp = new Date();
      Collection<Action> actions = new ArrayList<>();

      // go through each updated value
      for (String property : updatedValues.keySet()) {
        String newValue = updatedValues.get(property);
        String oldValue = values.get(property);
        Operation operation = null;

        // determine the type of operation
        if (oldValue == null || newValue == null || !newValue.equals(oldValue)) {
          operation = Operation.Configure;
        }

        // create a configuration action accordingly
        if (operation != null) {
          // clear the value if this property is sensitive
          final PropertyDescriptor propertyDescriptor =
              processor.getProcessor().getPropertyDescriptor(property);
          if (propertyDescriptor != null && propertyDescriptor.isSensitive()) {
            if (newValue != null) {
              newValue = "********";
            }
            if (oldValue != null) {
              oldValue = "********";
            }
          } else if (ANNOTATION_DATA.equals(property)) {
            if (newValue != null) {
              newValue = "<annotation data not shown>";
            }
            if (oldValue != null) {
              oldValue = "<annotation data not shown>";
            }
          }

          final FlowChangeConfigureDetails actionDetails = new FlowChangeConfigureDetails();
          actionDetails.setName(property);
          actionDetails.setValue(newValue);
          actionDetails.setPreviousValue(oldValue);

          // create a configuration action
          FlowChangeAction configurationAction = new FlowChangeAction();
          configurationAction.setUserIdentity(user.getIdentity());
          configurationAction.setUserName(user.getUserName());
          configurationAction.setOperation(operation);
          configurationAction.setTimestamp(actionTimestamp);
          configurationAction.setSourceId(processor.getIdentifier());
          configurationAction.setSourceName(processor.getName());
          configurationAction.setSourceType(Component.Processor);
          configurationAction.setComponentDetails(processorDetails);
          configurationAction.setActionDetails(actionDetails);
          actions.add(configurationAction);
        }
      }

      // determine the new executing state
      final ScheduledState updatedScheduledState = processor.getScheduledState();

      // determine if the running state has changed and its not disabled
      if (scheduledState != updatedScheduledState) {
        // create a processor action
        FlowChangeAction processorAction = new FlowChangeAction();
        processorAction.setUserIdentity(user.getIdentity());
        processorAction.setUserName(user.getUserName());
        processorAction.setTimestamp(new Date());
        processorAction.setSourceId(processor.getIdentifier());
        processorAction.setSourceName(processor.getName());
        processorAction.setSourceType(Component.Processor);
        processorAction.setComponentDetails(processorDetails);

        // set the operation accordingly
        if (ScheduledState.RUNNING.equals(updatedScheduledState)) {
          processorAction.setOperation(Operation.Start);
        } else if (ScheduledState.DISABLED.equals(updatedScheduledState)) {
          processorAction.setOperation(Operation.Disable);
        } else {
          // state is now stopped... consider the previous state
          if (ScheduledState.RUNNING.equals(scheduledState)) {
            processorAction.setOperation(Operation.Stop);
          } else if (ScheduledState.DISABLED.equals(scheduledState)) {
            processorAction.setOperation(Operation.Enable);
          }
        }
        actions.add(processorAction);
      }

      // ensure there are actions to record
      if (!actions.isEmpty()) {
        // save the actions
        saveActions(actions, logger);
      }
    }

    return updatedProcessor;
  }
Ejemplo n.º 9
0
  /**
   * Removes the specified access policy.
   *
   * @param httpServletRequest request
   * @param version The revision is used to verify the client is working with the latest version of
   *     the flow.
   * @param clientId Optional client id. If the client id is not specified, a new one will be
   *     generated. This value (whether specified or generated) is included in the response.
   * @param id The id of the access policy to remove.
   * @return A entity containing the client id and an updated revision.
   */
  @DELETE
  @Consumes(MediaType.WILDCARD)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{id}")
  // TODO - @PreAuthorize("hasRole('ROLE_DFM')")
  @ApiOperation(
      value = "Deletes an access policy",
      response = AccessPolicyEntity.class,
      authorizations = {@Authorization(value = "Data Flow Manager", type = "ROLE_DFM")})
  @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 removeAccessPolicy(
      @Context final HttpServletRequest httpServletRequest,
      @ApiParam(
              value =
                  "The revision is used to verify the client is working with the latest version of the flow.",
              required = false)
          @QueryParam(VERSION)
          final LongParameter version,
      @ApiParam(
              value =
                  "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
              required = false)
          @QueryParam(CLIENT_ID)
          @DefaultValue(StringUtils.EMPTY)
          final ClientIdParameter clientId,
      @ApiParam(value = "The access policy id.", required = true) @PathParam("id")
          final String id) {

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

    // handle expects request (usually from the cluster manager)
    final Revision revision =
        new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
        serviceFacade,
        revision,
        lookup -> {
          final Authorizable accessPolicy = lookup.getAccessPolicyById(id);
          accessPolicy.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        },
        () -> {},
        () -> {
          // delete the specified access policy
          final AccessPolicyEntity entity = serviceFacade.deleteAccessPolicy(revision, id);
          return clusterContext(generateOkResponse(entity)).build();
        });
  }
Ejemplo n.º 10
0
  /**
   * Updates an access policy.
   *
   * @param httpServletRequest request
   * @param id The id of the access policy to update.
   * @param accessPolicyEntity An accessPolicyEntity.
   * @return An accessPolicyEntity.
   */
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{id}")
  // TODO - @PreAuthorize("hasRole('ROLE_DFM')")
  @ApiOperation(
      value = "Updates a access policy",
      response = AccessPolicyEntity.class,
      authorizations = {@Authorization(value = "Data Flow Manager", type = "ROLE_DFM")})
  @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 updateAccessPolicy(
      @Context final HttpServletRequest httpServletRequest,
      @ApiParam(value = "The access policy id.", required = true) @PathParam("id") final String id,
      @ApiParam(value = "The access policy configuration details.", required = true)
          final AccessPolicyEntity accessPolicyEntity) {

    if (accessPolicyEntity == null || accessPolicyEntity.getComponent() == null) {
      throw new IllegalArgumentException("Access policy details must be specified.");
    }

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

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

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

    // Extract the revision
    final Revision revision = getRevision(accessPolicyEntity, id);
    return withWriteLock(
        serviceFacade,
        revision,
        lookup -> {
          Authorizable authorizable = lookup.getAccessPolicyById(id);
          authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        },
        null,
        () -> {
          // update the access policy
          final AccessPolicyEntity entity =
              serviceFacade.updateAccessPolicy(revision, accessPolicyDTO);
          populateRemainingAccessPolicyEntityContent(entity);

          return clusterContext(generateOkResponse(entity)).build();
        });
  }
Ejemplo n.º 11
0
  /**
   * Creates a new access policy.
   *
   * @param httpServletRequest request
   * @param accessPolicyEntity An accessPolicyEntity.
   * @return An accessPolicyEntity.
   */
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  // TODO - @PreAuthorize("hasRole('ROLE_DFM')")
  @ApiOperation(
      value = "Creates an access policy",
      response = AccessPolicyEntity.class,
      authorizations = {@Authorization(value = "Data Flow Manager", type = "ROLE_DFM")})
  @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 createAccessPolicy(
      @Context final HttpServletRequest httpServletRequest,
      @ApiParam(value = "The access policy configuration details.", required = true)
          final AccessPolicyEntity accessPolicyEntity) {

    if (accessPolicyEntity == null || accessPolicyEntity.getComponent() == null) {
      throw new IllegalArgumentException("Access policy details must be specified.");
    }

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

    final AccessPolicyDTO requestAccessPolicy = accessPolicyEntity.getComponent();
    if (requestAccessPolicy.getId() != null) {
      throw new IllegalArgumentException("Access policy ID cannot be specified.");
    }

    if (requestAccessPolicy.getResource() == null) {
      throw new IllegalArgumentException("Access policy resource must be specified.");
    }

    // ensure this is a valid action
    RequestAction.valueOfValue(requestAccessPolicy.getAction());

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

    // handle expects request (usually from the cluster manager)
    final boolean validationPhase = isValidationPhase(httpServletRequest);
    if (validationPhase || !isTwoPhaseRequest(httpServletRequest)) {
      // authorize access
      serviceFacade.authorizeAccess(
          lookup -> {
            final Authorizable accessPolicies =
                lookup.getAccessPolicyByResource(requestAccessPolicy.getResource());
            accessPolicies.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
          });
    }
    if (validationPhase) {
      return generateContinueResponse().build();
    }

    // set the access policy id as appropriate
    requestAccessPolicy.setId(generateUuid());

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

    // create the access policy and generate the json
    final AccessPolicyEntity entity =
        serviceFacade.createAccessPolicy(revision, accessPolicyEntity.getComponent());
    populateRemainingAccessPolicyEntityContent(entity);

    // build the response
    return clusterContext(generateCreatedResponse(URI.create(entity.getUri()), entity)).build();
  }
Ejemplo n.º 12
0
  /**
   * Updates the specified output port.
   *
   * @param httpServletRequest request
   * @param id The id of the output port to update.
   * @param requestPortEntity A outputPortEntity.
   * @return A outputPortEntity.
   */
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{id}")
  @ApiOperation(
      value = "Updates an output port",
      response = PortEntity.class,
      authorizations = {@Authorization(value = "Write - /output-ports/{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 updateOutputPort(
      @Context final HttpServletRequest httpServletRequest,
      @ApiParam(value = "The output port id.", required = true) @PathParam("id") final String id,
      @ApiParam(value = "The output port configuration details.", required = true)
          final PortEntity requestPortEntity) {

    if (requestPortEntity == null || requestPortEntity.getComponent() == null) {
      throw new IllegalArgumentException("Output port details must be specified.");
    }

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

    // ensure the ids are the same
    PortDTO requestPortDTO = requestPortEntity.getComponent();
    if (!id.equals(requestPortDTO.getId())) {
      throw new IllegalArgumentException(
          String.format(
              "The output port id (%s) in the request body does not equal the "
                  + "output port id of the requested resource (%s).",
              requestPortDTO.getId(), id));
    }

    final PositionDTO proposedPosition = requestPortDTO.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, requestPortEntity);
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestPortEntity, id);
    return withWriteLock(
        serviceFacade,
        requestPortEntity,
        requestRevision,
        lookup -> {
          Authorizable authorizable = lookup.getOutputPort(id);
          authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        },
        () -> serviceFacade.verifyUpdateOutputPort(requestPortDTO),
        (revision, portEntity) -> {
          final PortDTO portDTO = portEntity.getComponent();

          // update the output port
          final PortEntity entity = serviceFacade.updateOutputPort(revision, portDTO);
          populateRemainingOutputPortEntityContent(entity);

          return clusterContext(generateOkResponse(entity)).build();
        });
  }
Ejemplo n.º 13
0
 /**
  * Builds the proxy chain for the specified user.
  *
  * @param user The current user
  * @return The proxy chain for that user in String form
  */
 public static String buildProxiedEntitiesChainString(final NiFiUser user) {
   // calculate the dn chain
   final List<String> proxyChain = NiFiUserUtils.buildProxiedEntitiesChain(user);
   return formatProxyDn(StringUtils.join(proxyChain, "><"));
 }