use of org.apache.nifi.authorization.user.NiFiUser in project nifi by apache.
the class DataTransferResource method constructPeer.
private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream, final OutputStream outputStream, final String portId, final String transactionId) {
String clientHostName = req.getRemoteHost();
try {
// req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
final InetAddress clientAddress = InetAddress.getByName(clientHostName);
clientHostName = clientAddress.getHostName();
} catch (UnknownHostException e) {
logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
}
final int clientPort = req.getRemotePort();
final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());
final NiFiUser user = NiFiUserUtils.getNiFiUser();
final String userDn = user == null ? null : user.getIdentity();
final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream, outputStream, transactionId, userDn);
boolean useCompression = false;
final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
useCompression = true;
}
final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);
commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));
if (!isEmpty(requestExpiration)) {
commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
}
if (!isEmpty(batchCount)) {
commSession.putHandshakeParam(BATCH_COUNT, batchCount);
}
if (!isEmpty(batchSize)) {
commSession.putHandshakeParam(BATCH_SIZE, batchSize);
}
if (!isEmpty(batchDuration)) {
commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
}
if (peerDescription.isSecure()) {
final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
logger.debug("initiating peer, nifiUser={}", nifiUser);
commSession.setUserDn(nifiUser.getIdentity());
}
// TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
final String clusterUrl = "nifi://localhost:" + req.getLocalPort();
return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}
use of org.apache.nifi.authorization.user.NiFiUser in project nifi by apache.
the class FlowResource method getComponentHistory.
/**
* Gets the actions for the specified component.
*
* @param componentId The id of the component.
* @return An processorHistoryEntity.
*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("history/components/{componentId}")
@ApiOperation(value = "Gets configuration history for a component", notes = NON_GUARANTEED_ENDPOINT, response = ComponentHistoryEntity.class, authorizations = { @Authorization(value = "Read - /flow"), @Authorization(value = "Read underlying component - /{component-type}/{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 getComponentHistory(@ApiParam(value = "The component id.", required = true) @PathParam("componentId") final String componentId) {
serviceFacade.authorizeAccess(lookup -> {
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// authorize the flow
authorizeFlow();
try {
final Authorizable authorizable = lookup.getProcessor(componentId).getAuthorizable();
authorizable.authorize(authorizer, RequestAction.READ, user);
return;
} catch (final ResourceNotFoundException e) {
// ignore as the component may not be a processor
}
try {
final Authorizable authorizable = lookup.getControllerService(componentId).getAuthorizable();
authorizable.authorize(authorizer, RequestAction.READ, user);
return;
} catch (final ResourceNotFoundException e) {
// ignore as the component may not be a controller service
}
try {
final Authorizable authorizable = lookup.getReportingTask(componentId).getAuthorizable();
authorizable.authorize(authorizer, RequestAction.READ, user);
return;
} catch (final ResourceNotFoundException e) {
// ignore as the component may not be a reporting task
}
// a component for the specified id could not be found, attempt to authorize based on read to the controller
final Authorizable controller = lookup.getController();
controller.authorize(authorizer, RequestAction.READ, user);
});
// Note: History requests are not replicated throughout the cluster and are instead handled by the nodes independently
// create the response entity
final ComponentHistoryEntity entity = new ComponentHistoryEntity();
entity.setComponentHistory(serviceFacade.getComponentHistory(componentId));
// generate the response
return generateOkResponse(entity).build();
}
use of org.apache.nifi.authorization.user.NiFiUser in project nifi by apache.
the class ProcessGroupResource method instantiateTemplate.
/**
* Instantiates the specified template within this ProcessGroup. The template instance that is instantiated cannot be referenced at a later time, therefore there is no
* corresponding URI. Instead the request URI is returned.
* <p>
* Alternatively, we could have performed a PUT request. However, PUT requests are supposed to be idempotent and this endpoint is certainly not.
*
* @param httpServletRequest request
* @param groupId The group id
* @param requestInstantiateTemplateRequestEntity The instantiate template request
* @return A flowEntity.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/template-instance")
@ApiOperation(value = "Instantiates a template", response = FlowEntity.class, authorizations = { @Authorization(value = "Write - /process-groups/{uuid}"), @Authorization(value = "Read - /templates/{uuid}"), @Authorization(value = "Write - if the template contains any restricted components - /restricted-components") })
@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 instantiateTemplate(@Context HttpServletRequest httpServletRequest, @ApiParam(value = "The process group id.", required = true) @PathParam("id") String groupId, @ApiParam(value = "The instantiate template request.", required = true) InstantiateTemplateRequestEntity requestInstantiateTemplateRequestEntity) {
// ensure the position has been specified
if (requestInstantiateTemplateRequestEntity == null || requestInstantiateTemplateRequestEntity.getOriginX() == null || requestInstantiateTemplateRequestEntity.getOriginY() == null) {
throw new IllegalArgumentException("The origin position (x, y) must be specified.");
}
// ensure the template id was provided
if (requestInstantiateTemplateRequestEntity.getTemplateId() == null) {
throw new IllegalArgumentException("The template id must be specified.");
}
// ensure the template encoding version is valid
if (requestInstantiateTemplateRequestEntity.getEncodingVersion() != null) {
try {
FlowEncodingVersion.parse(requestInstantiateTemplateRequestEntity.getEncodingVersion());
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("The template encoding version is not valid. The expected format is <number>.<number>");
}
}
// populate the encoding version if necessary
if (requestInstantiateTemplateRequestEntity.getEncodingVersion() == null) {
// if the encoding version is not specified, use the latest encoding version as these options were
// not available pre 1.x, will be overridden if populating from the underlying template below
requestInstantiateTemplateRequestEntity.setEncodingVersion(TemplateDTO.MAX_ENCODING_VERSION);
}
// populate the component bundles if necessary
if (requestInstantiateTemplateRequestEntity.getSnippet() == null) {
// get the desired template in order to determine the supported bundles
final TemplateDTO requestedTemplate = serviceFacade.exportTemplate(requestInstantiateTemplateRequestEntity.getTemplateId());
final FlowSnippetDTO requestTemplateContents = requestedTemplate.getSnippet();
// determine the compatible bundles to use for each component in this template, this ensures the nodes in the cluster
// instantiate the components from the same bundles
discoverCompatibleBundles(requestTemplateContents);
// update the requested template as necessary - use the encoding version from the underlying template
requestInstantiateTemplateRequestEntity.setEncodingVersion(requestedTemplate.getEncodingVersion());
requestInstantiateTemplateRequestEntity.setSnippet(requestTemplateContents);
}
if (isReplicateRequest()) {
return replicate(HttpMethod.POST, requestInstantiateTemplateRequestEntity);
}
return withWriteLock(serviceFacade, requestInstantiateTemplateRequestEntity, lookup -> {
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// ensure write on the group
final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
processGroup.authorize(authorizer, RequestAction.WRITE, user);
final Authorizable template = lookup.getTemplate(requestInstantiateTemplateRequestEntity.getTemplateId());
template.authorize(authorizer, RequestAction.READ, user);
// ensure read on the template
final TemplateContentsAuthorizable templateContents = lookup.getTemplateContents(requestInstantiateTemplateRequestEntity.getSnippet());
final Consumer<ComponentAuthorizable> authorizeRestricted = authorizable -> {
if (authorizable.isRestricted()) {
authorizeRestrictions(authorizer, authorizable);
}
};
// ensure restricted access if necessary
templateContents.getEncapsulatedProcessors().forEach(authorizeRestricted);
templateContents.getEncapsulatedControllerServices().forEach(authorizeRestricted);
}, () -> serviceFacade.verifyComponentTypes(requestInstantiateTemplateRequestEntity.getSnippet()), instantiateTemplateRequestEntity -> {
// create the template and generate the json
final FlowEntity entity = serviceFacade.createTemplateInstance(groupId, instantiateTemplateRequestEntity.getOriginX(), instantiateTemplateRequestEntity.getOriginY(), instantiateTemplateRequestEntity.getEncodingVersion(), instantiateTemplateRequestEntity.getSnippet(), getIdGenerationSeed().orElse(null));
final FlowDTO flowSnippet = entity.getFlow();
// prune response as necessary
for (ProcessGroupEntity childGroupEntity : flowSnippet.getProcessGroups()) {
childGroupEntity.getComponent().setContents(null);
}
// create the response entity
populateRemainingSnippetContent(flowSnippet);
// generate the response
return generateCreatedResponse(getAbsolutePath(), entity).build();
});
}
use of org.apache.nifi.authorization.user.NiFiUser in project nifi by apache.
the class ProcessGroupResource method deleteVariableRegistryUpdateRequest.
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{groupId}/variable-registry/update-requests/{updateId}")
@ApiOperation(value = "Deletes an update request for a process group's variable registry. If the request is not yet complete, it will automatically be cancelled.", response = VariableRegistryUpdateRequestEntity.class, notes = NON_GUARANTEED_ENDPOINT, authorizations = { @Authorization(value = "Read - /process-groups/{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 deleteVariableRegistryUpdateRequest(@ApiParam(value = "The process group id.", required = true) @PathParam("groupId") final String groupId, @ApiParam(value = "The ID of the Variable Registry Update Request", required = true) @PathParam("updateId") final String updateId) {
if (groupId == null || updateId == null) {
throw new IllegalArgumentException("Group ID and Update ID must both be specified.");
}
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// authorize access
serviceFacade.authorizeAccess(lookup -> {
final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
processGroup.authorize(authorizer, RequestAction.READ, user);
processGroup.authorize(authorizer, RequestAction.WRITE, user);
});
final VariableRegistryUpdateRequest request = varRegistryUpdateRequests.remove(updateId);
if (request == null) {
throw new ResourceNotFoundException("Could not find a Variable Registry Update Request with identifier " + updateId);
}
if (!groupId.equals(request.getProcessGroupId())) {
throw new ResourceNotFoundException("Could not find a Variable Registry Update Request with identifier " + updateId + " for Process Group with identifier " + groupId);
}
if (!user.equals(request.getUser())) {
throw new IllegalArgumentException("Only the user that submitted the update request can remove it.");
}
request.cancel();
final VariableRegistryUpdateRequestEntity entity = new VariableRegistryUpdateRequestEntity();
entity.setRequest(dtoFactory.createVariableRegistryUpdateRequestDto(request));
entity.setProcessGroupRevision(request.getProcessGroupRevision());
entity.getRequest().setUri(generateResourceUri("process-groups", groupId, "variable-registry", updateId));
return generateOkResponse(entity).build();
}
use of org.apache.nifi.authorization.user.NiFiUser in project nifi by apache.
the class ProcessGroupResource method getVariableRegistryUpdateRequest.
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{groupId}/variable-registry/update-requests/{updateId}")
@ApiOperation(value = "Gets a process group's variable registry", response = VariableRegistryUpdateRequestEntity.class, notes = NON_GUARANTEED_ENDPOINT, authorizations = { @Authorization(value = "Read - /process-groups/{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 getVariableRegistryUpdateRequest(@ApiParam(value = "The process group id.", required = true) @PathParam("groupId") final String groupId, @ApiParam(value = "The ID of the Variable Registry Update Request", required = true) @PathParam("updateId") final String updateId) {
if (groupId == null || updateId == null) {
throw new IllegalArgumentException("Group ID and Update ID must both be specified.");
}
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// authorize access
serviceFacade.authorizeAccess(lookup -> {
final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
processGroup.authorize(authorizer, RequestAction.READ, user);
});
final VariableRegistryUpdateRequest request = varRegistryUpdateRequests.get(updateId);
if (request == null) {
throw new ResourceNotFoundException("Could not find a Variable Registry Update Request with identifier " + updateId);
}
if (!groupId.equals(request.getProcessGroupId())) {
throw new ResourceNotFoundException("Could not find a Variable Registry Update Request with identifier " + updateId + " for Process Group with identifier " + groupId);
}
if (!user.equals(request.getUser())) {
throw new IllegalArgumentException("Only the user that submitted the update request can retrieve it.");
}
final VariableRegistryUpdateRequestEntity entity = new VariableRegistryUpdateRequestEntity();
entity.setRequest(dtoFactory.createVariableRegistryUpdateRequestDto(request));
entity.setProcessGroupRevision(request.getProcessGroupRevision());
entity.getRequest().setUri(generateResourceUri("process-groups", groupId, "variable-registry", updateId));
return generateOkResponse(entity).build();
}
Aggregations