diff options
author | Jorge Hernandez <jorge.hernandez-herrero@att.com> | 2019-04-09 14:31:39 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-04-09 14:31:39 +0000 |
commit | 1b1640ae538cfdb3667fd3222dc4dec469b0e3f7 (patch) | |
tree | fb22c500d2cc72c240cf71164e7b909f4bfd65d2 /ONAP-PDP-REST/src/main/java | |
parent | 6da5838f43a4bf0dc8786c539f9a9aa521139e55 (diff) | |
parent | 6d72b847fe202bc1cd6fb3922755be774de0df69 (diff) |
Merge "Make clientAuth header optional and log request"
Diffstat (limited to 'ONAP-PDP-REST/src/main/java')
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java | 646 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java | 61 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java | 1 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java | 5 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PdpApiService.java | 1 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java | 60 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java | 117 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java (renamed from ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java) | 207 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/PdpAuthenticationFilter.java | 100 |
9 files changed, 676 insertions, 522 deletions
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java index 4296c058c..fd4f25529 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java @@ -20,6 +20,10 @@ package org.onap.policy.pdp.rest.api.controller; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; @@ -58,24 +62,22 @@ import org.onap.policy.pdp.rest.api.services.NotificationService.NotificationSer import org.onap.policy.pdp.rest.api.services.PolicyEngineImportService; import org.onap.policy.pdp.rest.api.services.PushPolicyService; import org.onap.policy.pdp.rest.api.services.SendEventService; -import org.onap.policy.pdp.rest.config.PDPApiAuth; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; import springfox.documentation.annotations.ApiIgnore; @RestController @@ -83,7 +85,6 @@ import springfox.documentation.annotations.ApiIgnore; @RequestMapping("/") public class PolicyEngineServices { private static Logger logger = FlexLogger.getLogger(PolicyEngineServices.class.getName()); - private static final String NOTIFICATIONPERM = "notification"; private final AtomicLong configCounter = new AtomicLong(); private final AtomicLong configNameCounter = new AtomicLong(); @@ -112,64 +113,72 @@ public class PolicyEngineServices { @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP)") - @RequestMapping(value = "/getConfig", method = RequestMethod.POST) + @PostMapping(value = "/getConfig") @ResponseBody public ResponseEntity<Collection<PolicyConfig>> getConfig( @RequestBody ConfigRequestParameters configRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { Collection<PolicyConfig> policyConfig = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfig")) { - GetConfigService getConfigService = new GetConfigService(configRequestParameters, requestID); - policyConfig = getConfigService.getResult(); - status = getConfigService.getResponseCode(); - } + GetConfigService getConfigService = new GetConfigService(configRequestParameters, requestId); + policyConfig = getConfigService.getResult(); + HttpStatus status = getConfigService.getResponseCode(); configCounter.incrementAndGet(); return new ResponseEntity<>(policyConfig, status); } + /** + * Gets the config by policy name. + * + * @param configNameRequest the config name request + * @param clientEncoding the client encoding + * @param requestId the request id + * @return the config by policy name + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName") - @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST) + @PostMapping(value = "/getConfigByPolicyName") @ResponseBody @Deprecated public ResponseEntity<Collection<PolicyConfig>> getConfigByPolicyName( @RequestBody ConfigNameRequest configNameRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { Collection<PolicyConfig> policyConfig = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfigByPolicyName")) { - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - configRequestParameters.setPolicyName(configNameRequest.getPolicyName()); - GetConfigService getConfigService = new GetConfigService(configRequestParameters, requestID); - policyConfig = getConfigService.getResult(); - status = getConfigService.getResponseCode(); - } + logger.info("Operation: getConfigByPolicyName - " + configNameRequest.getPolicyName()); + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(configNameRequest.getPolicyName()); + + GetConfigService getConfigService = new GetConfigService(configRequestParameters, requestId); + policyConfig = getConfigService.getResult(); + HttpStatus status = getConfigService.getResponseCode(); configNameCounter.incrementAndGet(); return new ResponseEntity<>(policyConfig, status); } + + /** + * List config. + * + * @param configRequestParameters the config request parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the list of configuration policies from the PDP") - @RequestMapping(value = "/listConfig", method = RequestMethod.POST) + @PostMapping(value = "/listConfig") @ResponseBody public ResponseEntity<Collection<String>> listConfig(@RequestBody ConfigRequestParameters configRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { Collection<String> results = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "listConfig")) { - ListConfigService listConfigService = new ListConfigService(configRequestParameters, requestID); - results = listConfigService.getResult(); - status = listConfigService.getResponseCode(); - } + logger.info("Operation: listConfig - " + configRequestParameters); + ListConfigService listConfigService = new ListConfigService(configRequestParameters, requestId); + results = listConfigService.getResult(); + HttpStatus status = listConfigService.getResponseCode(); configCounter.incrementAndGet(); return new ResponseEntity<>(results, status); } @@ -188,422 +197,524 @@ public class PolicyEngineServices { @PostMapping(value = "/listPolicy") @ResponseBody public ResponseEntity<Collection<String>> listPolicy(@RequestBody ConfigNameRequest configNameRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { Collection<String> results = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; logger.info("Operation: listPolicy - " + configNameRequest); - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestId, "listPolicy")) { - ListPolicyService listPolicyService = new ListPolicyService(configNameRequest); - results = listPolicyService.getResult(); - status = listPolicyService.getResponseCode(); - } + ListPolicyService listPolicyService = new ListPolicyService(configNameRequest); + results = listPolicyService.getResult(); + HttpStatus status = listPolicyService.getResponseCode(); configCounter.incrementAndGet(); return new ResponseEntity<>(results, status); } + /** + * Gets the metrics. + * + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the metrics + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the policy metrics from the PolicyAccessPoint(PAP)") - @RequestMapping(value = "/getMetrics", method = RequestMethod.GET) + @GetMapping(value = "/getMetrics") @ResponseBody public ResponseEntity<MetricsResponse> getMetrics( - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { MetricsResponse response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getMetrics")) { - GetMetricsService getMetricsService = new GetMetricsService(requestID); - response = getMetricsService.getResult(); - status = getMetricsService.getResponseCode(); - } + logger.info("Operation: getMetrics"); + + GetMetricsService getMetricsService = new GetMetricsService(requestId); + response = getMetricsService.getResult(); + HttpStatus status = getMetricsService.getResponseCode(); metricCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Gets the notification. + * + * @param notificationTopic the notification topic + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the notification + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Registers DMaaP Topic to recieve notification from Policy Engine") - @RequestMapping(value = "/getNotification", method = RequestMethod.POST) + @PostMapping(value = "/getNotification") @ResponseBody public ResponseEntity<String> getNotification(@RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Notification Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = - new NotificationService(notificationTopic, requestID, NotificationServiceType.ADD); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: getNotification for Topic: " + notificationTopic); + + NotificationService notificationService = + new NotificationService(notificationTopic, requestId, NotificationServiceType.ADD); + String policyResponse = notificationService.getResult(); + HttpStatus status = notificationService.getResponseCode(); notificationCounter.incrementAndGet(); return new ResponseEntity<>(policyResponse, status); } + /** + * Stop notification. + * + * @param notificationTopic the notification topic + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "De-Registers DMaaP Topic to stop recieving notifications from Policy Engine") - @RequestMapping(value = "/stopNotification", method = RequestMethod.POST) + @PostMapping(value = "/stopNotification") @ResponseBody public ResponseEntity<String> stopNotification(@RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Notification Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = - new NotificationService(notificationTopic, requestID, NotificationServiceType.REMOVE); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: stopNotification for Topic: " + notificationTopic); + + NotificationService notificationService = + new NotificationService(notificationTopic, requestId, NotificationServiceType.REMOVE); + String policyResponse = notificationService.getResult(); + HttpStatus status = notificationService.getResponseCode(); + notificationCounter.incrementAndGet(); return new ResponseEntity<>(policyResponse, status); } + /** + * Send heartbeat. + * + * @param notificationTopic the notification topic + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation( value = "Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine") - @RequestMapping(value = "/sendHeartbeat", method = RequestMethod.POST) + @PostMapping(value = "/sendHeartbeat") @ResponseBody public ResponseEntity<String> sendHeartbeat(@RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Heartbeat Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = - new NotificationService(notificationTopic, requestID, NotificationServiceType.HB); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: sendHeartbeat for topic - " + notificationTopic); + + NotificationService notificationService = + new NotificationService(notificationTopic, requestId, NotificationServiceType.HB); + String policyResponse = notificationService.getResult(); + HttpStatus status = notificationService.getResponseCode(); + return new ResponseEntity<>(policyResponse, status); } + /** + * Send event. + * + * @param eventRequestParameters the event request parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Sends the Events specified to the Policy Engine") - @RequestMapping(value = "/sendEvent", method = RequestMethod.POST) + @PostMapping(value = "/sendEvent") @ResponseBody public ResponseEntity<Collection<PolicyResponse>> sendEvent( @RequestBody EventRequestParameters eventRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { Collection<PolicyResponse> policyResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "sendEvent")) { - SendEventService sendEventService = new SendEventService(eventRequestParameters, requestID); - policyResponse = sendEventService.getResult(); - status = sendEventService.getResponseCode(); - } + logger.info("Operation: sendEvent with EventAttributes - " + eventRequestParameters.getEventAttributes()); + + SendEventService sendEventService = new SendEventService(eventRequestParameters, requestId); + policyResponse = sendEventService.getResult(); + HttpStatus status = sendEventService.getResponseCode(); eventCounter.incrementAndGet(); return new ResponseEntity<>(policyResponse, status); } + /** + * Gets the decision. + * + * @param decisionRequestParameters the decision request parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the decision + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the Decision using specified decision parameters") - @RequestMapping(value = "/getDecision", method = RequestMethod.POST) + @PostMapping(value = "/getDecision") @ResponseBody public ResponseEntity<DecisionResponse> getDecision( @RequestBody DecisionRequestParameters decisionRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { DecisionResponse decisionResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getDecision")) { - GetDecisionService getDecisionService = new GetDecisionService(decisionRequestParameters, requestID); - decisionResponse = getDecisionService.getResult(); - status = getDecisionService.getResponseCode(); - } + + GetDecisionService getDecisionService = new GetDecisionService(decisionRequestParameters, requestId); + decisionResponse = getDecisionService.getResult(); + HttpStatus status = getDecisionService.getResponseCode(); decisionCounter.incrementAndGet(); return new ResponseEntity<>(decisionResponse, status); } + /** + * Push policy. + * + * @param pushPolicyParameters the push policy parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Pushes the specified policy to the PDP Group.") - @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT) + @PutMapping(value = "/pushPolicy") @ResponseBody public ResponseEntity<String> pushPolicy(@RequestBody PushPolicyParameters pushPolicyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestAttribute(name = "Mechid") String mechId, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "pushPolicy")) { - PushPolicyService pushPolicyService = new PushPolicyService(pushPolicyParameters, requestID); - response = pushPolicyService.getResult(); - status = pushPolicyService.getResponseCode(); - } + logger.info("Operation: pushPolicy - " + pushPolicyParameters + ", Mechid - " + mechId); + PushPolicyService pushPolicyService = new PushPolicyService(pushPolicyParameters, requestId); + response = pushPolicyService.getResult(); + HttpStatus status = pushPolicyService.getResponseCode(); pushCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Delete policy. + * + * @param deletePolicyParameters the delete policy parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Deletes the specified policy from the PDP Group or PAP.") - @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE) + @DeleteMapping(value = "/deletePolicy") @ResponseBody public ResponseEntity<String> deletePolicy(@RequestBody DeletePolicyParameters deletePolicyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestAttribute(name = "Mechid") String mechId, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "deletePolicy")) { - DeletePolicyService deletePolicyService = new DeletePolicyService(deletePolicyParameters, requestID); - response = deletePolicyService.getResult(); - status = deletePolicyService.getResponseCode(); - } + logger.info("Operation: deletePolicy - " + deletePolicyParameters + ", Mechid - " + mechId); + DeletePolicyService deletePolicyService = new DeletePolicyService(deletePolicyParameters, requestId); + response = deletePolicyService.getResult(); + HttpStatus status = deletePolicyService.getResponseCode(); deleteCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Creates the policy. + * + * @param policyParameters the policy parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Creates a Policy based on given Policy Parameters.") - @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT) + @PutMapping(value = "/createPolicy") @ResponseBody public ResponseEntity<String> createPolicy(@RequestBody PolicyParameters policyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestAttribute(name = "Mechid") String mechId, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { String response = null; HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "createPolicy")) { - CreateUpdatePolicyService createPolicyService; - try { - createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor() - .newInstance(policyParameters, requestID, false); - response = createPolicyService.getResult(); - status = createPolicyService.getResponseCode(); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - logger.error(e.getMessage(), e); - response = "Problem with CreateUpdate Policy Service. "; - status = HttpStatus.INTERNAL_SERVER_ERROR; - } + logger.info("Operation: createPolicy for " + policyParameters.toString() + ", Mechid : " + mechId); + + CreateUpdatePolicyService createPolicyService; + try { + createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor() + .newInstance(policyParameters, requestId, false); + response = createPolicyService.getResult(); + status = createPolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + logger.error(e.getMessage(), e); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; } createPolicyCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Update policy. + * + * @param policyParameters the policy parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Updates a Policy based on given Policy Parameters.") - @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT) + @PutMapping(value = "/updatePolicy") @ResponseBody public ResponseEntity<String> updatePolicy(@RequestBody PolicyParameters policyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestAttribute(name = "Mechid") String mechId, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { String response = null; HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "updatePolicy")) { - CreateUpdatePolicyService updatePolicyService; - try { - updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor() - .newInstance(policyParameters, requestID, true); - response = updatePolicyService.getResult(); - status = updatePolicyService.getResponseCode(); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - logger.error(e.getMessage(), e); - response = "Problem with CreateUpdate Policy Service. "; - status = HttpStatus.INTERNAL_SERVER_ERROR; - } + logger.info("Operation: updatePolicy for " + policyParameters.toString() + ", MechId - " + mechId); + + CreateUpdatePolicyService updatePolicyService; + try { + updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor() + .newInstance(policyParameters, requestId, true); + response = updatePolicyService.getResult(); + status = updatePolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + logger.error(e.getMessage(), e); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; } updatePolicyCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Creates the dictionary item. + * + * @param dictionaryParameters the dictionary parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Creates a Dictionary Item for a specific dictionary based on given Parameters.") - @RequestMapping(value = "/createDictionaryItem", method = RequestMethod.PUT) + @PutMapping(value = "/createDictionaryItem") @ResponseBody public ResponseEntity<String> createDictionaryItem(@RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "createDictionary")) { - CreateUpdateDictionaryService createDictionaryService = - new CreateUpdateDictionaryService(dictionaryParameters, requestID, false); - response = createDictionaryService.getResult(); - status = createDictionaryService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: createDictionaryItem - " + dictionaryParameters); + + CreateUpdateDictionaryService createDictionaryService = + new CreateUpdateDictionaryService(dictionaryParameters, requestId, false); + String response = createDictionaryService.getResult(); + HttpStatus status = createDictionaryService.getResponseCode(); createDictionaryCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Update dictionary item. + * + * @param dictionaryParameters the dictionary parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Updates a Dictionary Item for a specific dictionary based on given Parameters.") - @RequestMapping(value = "/updateDictionaryItem", method = RequestMethod.PUT) + @PutMapping(value = "/updateDictionaryItem") @ResponseBody public ResponseEntity<String> updateDictionaryItem(@RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "updateDictionary")) { - CreateUpdateDictionaryService updateDictionaryService = - new CreateUpdateDictionaryService(dictionaryParameters, requestID, true); - response = updateDictionaryService.getResult(); - status = updateDictionaryService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: updateDictionaryItem - " + dictionaryParameters); + + CreateUpdateDictionaryService updateDictionaryService = + new CreateUpdateDictionaryService(dictionaryParameters, requestId, true); + String response = updateDictionaryService.getResult(); + HttpStatus status = updateDictionaryService.getResponseCode(); updateDictionaryCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Gets the dictionary items. + * + * @param dictionaryParameters the dictionary parameters + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the dictionary items + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Gets the dictionary items from the PAP") - @RequestMapping(value = "/getDictionaryItems", method = RequestMethod.POST) + @PostMapping(value = "/getDictionaryItems") @ResponseBody public ResponseEntity<DictionaryResponse> getDictionaryItems(@RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { DictionaryResponse dictionaryResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getDictionary")) { - GetDictionaryService getDictionaryService = new GetDictionaryService(dictionaryParameters, requestID); - dictionaryResponse = getDictionaryService.getResult(); - status = getDictionaryService.getResponseCode(); - } + logger.info("Operation: getDictionaryItems - " + dictionaryParameters); + GetDictionaryService getDictionaryService = new GetDictionaryService(dictionaryParameters, requestId); + dictionaryResponse = getDictionaryService.getResult(); + HttpStatus status = getDictionaryService.getResponseCode(); getDictionaryCounter.incrementAndGet(); return new ResponseEntity<>(dictionaryResponse, status); } + /** + * Policy engine import. + * + * @param importParametersJson the import parameters json + * @param file the file + * @param clientEncoding the client encoding + * @param requestId the request ID + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) - @ApiOperation( - value = "Imports Policy based on the parameters which represent the service used to create a policy Service.") - @RequestMapping(value = "/policyEngineImport", method = RequestMethod.POST) + @ApiOperation(value = "Imports models and templates which represent the service used to create a policy.") + @PostMapping(value = "/policyEngineImport") @ResponseBody public ResponseEntity<String> policyEngineImport(@RequestParam("importParametersJson") String importParametersJson, @RequestParam("file") MultipartFile file, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "policyEngineImport")) { - PolicyEngineImportService policyEngineImportService = - new PolicyEngineImportService(importParametersJson, file, requestID); - response = policyEngineImportService.getResult(); - status = policyEngineImportService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: policyEngineImport with importParametersJson: " + importParametersJson); + PolicyEngineImportService policyEngineImportService = + new PolicyEngineImportService(importParametersJson, file, requestId); + String response = policyEngineImportService.getResult(); + HttpStatus status = policyEngineImportService.getResponseCode(); policyEngineImportCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Creates the config. + * + * @param configPolicyAPIRequest the config policy API request + * @param clientEncoding the client encoding + * @param requestId the request id + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Creates a Config Policy based on given Policy Parameters.") - @RequestMapping(value = "/createConfig", method = RequestMethod.PUT) + @PutMapping(value = "/createConfig") @ResponseBody @Deprecated public ResponseEntity<String> createConfig(@RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "createPolicy")) { - CreateUpdateConfigPolicyService createPolicyService = - new CreateUpdateConfigPolicyService(configPolicyAPIRequest, requestID, false); - response = createPolicyService.getResult(); - status = createPolicyService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: createConfig"); + + CreateUpdateConfigPolicyService createPolicyService = + new CreateUpdateConfigPolicyService(configPolicyAPIRequest, requestId, false); + String response = createPolicyService.getResult(); + HttpStatus status = createPolicyService.getResponseCode(); deprecatedCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Update config. + * + * @param configPolicyAPIRequest the config policy API request + * @param clientEncoding the client encoding + * @param requestId the request id + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Updates a Config Policy based on given Policy Parameters.") - @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT) + @PutMapping(value = "/updateConfig") @ResponseBody @Deprecated public ResponseEntity<String> updateConfig(@RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "updatePolicy")) { - CreateUpdateConfigPolicyService updatePolicyService = - new CreateUpdateConfigPolicyService(configPolicyAPIRequest, requestID, true); - response = updatePolicyService.getResult(); - status = updatePolicyService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: updateConfig"); + + CreateUpdateConfigPolicyService updatePolicyService = + new CreateUpdateConfigPolicyService(configPolicyAPIRequest, requestId, true); + String response = updatePolicyService.getResult(); + HttpStatus status = updatePolicyService.getResponseCode(); deprecatedCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Creates the firewall config. + * + * @param configFirewallPolicyAPIRequest the config firewall policy API request + * @param clientEncoding the client encoding + * @param requestId the request id + * @return the response entity + */ + @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Creates a Config Firewall Policy") - @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT) + @PutMapping(value = "/createFirewallConfig") @ResponseBody @Deprecated public ResponseEntity<String> createFirewallConfig( @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "createPolicy")) { - CreateUpdateFirewallPolicyService createFirewallPolicyService = - new CreateUpdateFirewallPolicyService(configFirewallPolicyAPIRequest, requestID, false); - response = createFirewallPolicyService.getResult(); - status = createFirewallPolicyService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: createFirewallConfig"); + + CreateUpdateFirewallPolicyService createFirewallPolicyService = + new CreateUpdateFirewallPolicyService(configFirewallPolicyAPIRequest, requestId, false); + String response = createFirewallPolicyService.getResult(); + HttpStatus status = createFirewallPolicyService.getResponseCode(); deprecatedCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Update firewall config. + * + * @param configFirewallPolicyAPIRequest the config firewall policy API request + * @param clientEncoding the client encoding + * @param requestId the request id + * @return the response entity + */ @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @ApiImplicitParam(name = "Environment", required = true, paramType = "Header")}) @ApiOperation(value = "Updates a Config Firewall Policy") - @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT) + @PutMapping(value = "/updateFirewallConfig") @ResponseBody @Deprecated public ResponseEntity<String> updateFirewallConfig( @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "updatePolicy")) { - CreateUpdateFirewallPolicyService updateFirewallPolicyService = - new CreateUpdateFirewallPolicyService(configFirewallPolicyAPIRequest, requestID, true); - response = updateFirewallPolicyService.getResult(); - status = updateFirewallPolicyService.getResponseCode(); - } + @RequestHeader(value = "ClientAuth", required = false) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestId) { + logger.info("Operation: updateFirewallConfig"); + + CreateUpdateFirewallPolicyService updateFirewallPolicyService = + new CreateUpdateFirewallPolicyService(configFirewallPolicyAPIRequest, requestId, true); + String response = updateFirewallPolicyService.getResult(); + HttpStatus status = updateFirewallPolicyService.getResponseCode(); deprecatedCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + /** + * Gets the count. + * + * @return the count + */ @ApiOperation(value = "Gets the API Services usage Information") @ApiIgnore - @RequestMapping(value = "/count", method = RequestMethod.GET) + @GetMapping(value = "/count") public String getCount() { return "Total Config Calls : " + configCounter + "\n" + "Total Config calls made using Policy File Name: " + configNameCounter + "\n" + "Total Event Calls : " + eventCounter + "\nTotal Decision Calls: " @@ -616,6 +727,13 @@ public class PolicyEngineServices { + "\nTotal Metrics Calls:" + metricCounter + "\nTotal Notification Calls:" + notificationCounter; } + /** + * Message not readable exception handler. + * + * @param req the req + * @param exception the exception + * @return the response entity + */ @ExceptionHandler({HttpMessageNotReadableException.class}) public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java index 3614bac08..33865d3e0 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,17 +19,18 @@ */ package org.onap.policy.pdp.rest.api.models; +import com.google.gson.Gson; import io.swagger.annotations.ApiModel; import java.util.Map; - import org.onap.policy.api.PolicyConfigStatus; import org.onap.policy.api.PolicyConfigType; import org.onap.policy.api.PolicyType; import org.onap.policy.models.APIConfigResponse; @ApiModel -public class PolicyConfig implements APIConfigResponse{ +public class PolicyConfig implements APIConfigResponse { + private static final Gson GSON = new Gson(); private String policyConfigMessage; private PolicyConfigStatus policyConfigStatus; private PolicyType type; @@ -40,64 +41,98 @@ public class PolicyConfig implements APIConfigResponse{ private Map<String, String> matchingConditions; private Map<String, String> responseAttributes; private Map<String, String> property; + + @Override public String getConfig() { return config; } + public void setConfig(String config) { this.config = config; } + + @Override public PolicyType getType() { return type; } + public void setType(PolicyType type) { this.type = type; } + + @Override public PolicyConfigStatus getPolicyConfigStatus() { return policyConfigStatus; } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { this.policyConfigStatus = policyConfigStatus; } + + @Override public String getPolicyConfigMessage() { return policyConfigMessage; } + public void setPolicyConfigMessage(String policyConfigMessage) { this.policyConfigMessage = policyConfigMessage; } + + @Override public Map<String, String> getProperty() { return property; } + public void setProperty(Map<String, String> property) { this.property = property; } - public String getPolicyName(){ + + @Override + public String getPolicyName() { return policyName; } - public void setPolicyName(String policyName){ + + public void setPolicyName(String policyName) { this.policyName = policyName; } - public String getPolicyVersion(){ + + @Override + public String getPolicyVersion() { return policyVersion; } - public void setPolicyVersion(String policyVersion){ + + public void setPolicyVersion(String policyVersion) { this.policyVersion = policyVersion; } - public Map<String, String> getMatchingConditions(){ + + @Override + public Map<String, String> getMatchingConditions() { return matchingConditions; } - public void setMatchingConditions(Map<String, String> matchingConditions){ + + public void setMatchingConditions(Map<String, String> matchingConditions) { this.matchingConditions = matchingConditions; } - public void setResponseAttributes(Map<String,String> responseAttributes){ + + public void setResponseAttributes(Map<String, String> responseAttributes) { this.responseAttributes = responseAttributes; } - public Map<String,String> getResponseAttributes(){ + + @Override + public Map<String, String> getResponseAttributes() { return responseAttributes; } + public PolicyConfigType getPolicyType() { return policyType; } + public void setPolicyType(PolicyConfigType policyType) { this.policyType = policyType; } + + @Override + public String toString() { + return GSON.toJson(this); + } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java index 4f7384b3d..a004330f6 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java @@ -43,7 +43,6 @@ import org.springframework.http.HttpStatus; public class DeletePolicyService extends PdpApiService { private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); - private static final String PRINT_REQUESTID = " - RequestId - "; private DeletePolicyParameters deletePolicyParameters = null; private String result = null; private List<PolicyNameType> policyList = new ArrayList<>(); diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java index 7704a96a6..822599f13 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java @@ -40,7 +40,7 @@ import org.apache.commons.io.IOUtils; import org.onap.policy.api.PolicyException; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pdp.rest.config.PDPApiAuth; +import org.onap.policy.pdp.rest.restauth.AuthenticationService; import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -64,7 +64,7 @@ public class PAPServices { } public PAPServices() { - environment = PDPApiAuth.getEnvironment(); + environment = AuthenticationService.getEnvironment(); if (paps == null) { synchronized (papResourceLock) { String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); @@ -331,6 +331,7 @@ public class PAPServices { private String checkResponse(final HttpURLConnection connection, final UUID requestID) throws IOException { String response = null; + LOGGER.info("PAPServices:checkResponse - RequestId: " + requestID + ", ResponseCode: " + responseCode); if (responseCode == 200 || isJunit) { // Check for successful creation of policy String isSuccess = null; diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PdpApiService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PdpApiService.java index 4d38753bf..8a7a8e0a0 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PdpApiService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PdpApiService.java @@ -31,6 +31,7 @@ import org.springframework.http.HttpStatus; public abstract class PdpApiService { private static final Logger LOGGER = FlexLogger.getLogger(PdpApiService.class.getName()); + protected static final String PRINT_REQUESTID = " - RequestId - "; protected String requestId = null; protected String filePrefix = null; protected String clientScope = null; diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java deleted file mode 100644 index b1b092431..000000000 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PDP-REST - * ================================================================================ - * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pdp.rest.restAuth; - -import com.att.research.xacml.util.XACMLProperties; -import java.util.Base64; -import java.util.StringTokenizer; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.utils.PeCryptoUtils; - -public class AuthenticationService { - private String pdpID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_USERID); - private String pdpPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS)); - - public boolean authenticate(String authCredentials) { - - if (null == authCredentials) - return false; - // header value format will be "Basic encodedstring" for Basic authentication. - final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); - String usernameAndPassword = null; - try { - byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - return false; - } - try { - final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - final String username = tokenizer.nextToken(); - final String password = tokenizer.nextToken(); - return pdpID.equals(username) && pdpPass.equals(password); - }catch (Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - return false; - } - } - -} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java deleted file mode 100644 index 5b01ca9e5..000000000 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PDP-REST - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pdp.rest.restAuth; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.policy.pdp.rest.config.PDPApiAuth; - -/** - * Servlet Filter implementation class PDPAuthenticationFilter - */ -@WebFilter("/*") -public class PDPAuthenticationFilter implements Filter { - - public static final String AUTHENTICATION_HEADER = "Authorization"; - public static final String ENVIRONMENT_HEADER = "Environment"; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - if (request instanceof HttpServletRequest) { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); - String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); - String path = ((HttpServletRequest) request).getRequestURI(); - // better injected - AuthenticationService authenticationService = new AuthenticationService(); - - boolean authenticationStatus = authenticationService.authenticate(authCredentials); - - if (authenticationStatus) { - if (check(path)) { - // New API request. - path = path.substring(path.substring(1).indexOf("/") + 1); - if (environment == null) { - // Allow Old clients. - if(!path.contains("/api/")){ - request.getRequestDispatcher("/api/" + path).forward(request,response); - }else{ - request.getRequestDispatcher(path).forward(request,response); - } - } else if (environment.equalsIgnoreCase(PDPApiAuth.getEnvironment())) { - // Validated new Clients. - if(!path.contains("/api/")){ - request.getRequestDispatcher("/api/" + path).forward(request,response); - }else{ - request.getRequestDispatcher(path).forward(request,response); - } - } else if(response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } else { - filter.doFilter(request, response); - } - } else if (path.contains("swagger") || path.contains("api-docs") - || path.contains("configuration") || path.contains("count")) { - path = path.substring(path.substring(1).indexOf("/") + 2); - request.getRequestDispatcher("/api/" + path).forward(request,response); - } else if(path.contains("notifications")){ - filter.doFilter(request, response); - } else { - if (response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } - } - } - - private boolean check(String path) { - if(path.endsWith("/pdp/")|| path.endsWith("/pdp")|| path.endsWith("/test")){ - return false; - }else{ - return true; - } - } - - @Override - public void destroy() { - // Do nothing. - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - // Do nothing. - } - -} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java index 163298186..87a46aa23 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.pdp.rest.config; +package org.onap.policy.pdp.rest.restauth; import com.att.research.xacml.util.XACMLProperties; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -35,6 +36,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; +import javax.servlet.ServletRequest; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.api.PolicyEngineException; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -46,23 +49,22 @@ import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; -public class PDPApiAuth { - private static final Logger LOGGER = FlexLogger.getLogger(PDPApiAuth.class); - +public class AuthenticationService { + private static final Logger LOGGER = FlexLogger.getLogger(AuthenticationService.class); private static String environment = null; private static Path clientPath = null; private static Map<String, ArrayList<String>> clientMap = null; private static Long oldModified = null; private static AAFPolicyClient aafClient = null; - private PDPApiAuth() { + private AuthenticationService() { // Private Constructor } /* * Set Property by reading the properties File. */ - public static void setProperty() { + private static void setProperty() { environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE); if (clientFile != null) { @@ -75,8 +77,10 @@ public class PDPApiAuth { } } - /* - * Return Environment value of the PDP servlet. + /** + * Gets the environment. + * + * @return the environment */ public static String getEnvironment() { if (environment == null) { @@ -85,54 +89,80 @@ public class PDPApiAuth { return environment; } - /* + private static String reverseNamespace(String namespace) { + final List<String> components = Arrays.asList(namespace.split("\\.")); + Collections.reverse(components); + return String.join(".", components); + } + + /** * Security check for authentication and authorizations. + * + * @param clientAuthHeader the client auth header + * @param authHeader the auth header + * @param resource the resource + * @param env the env + * @return true, if successful */ - public static boolean checkPermissions(String clientEncoding, String requestID, String resource) { + public static boolean checkPermissions(String clientAuthHeader, String authHeader, String resource, String env, + ServletRequest request) { + boolean result = false; + // check whether env matches + result = checkEnv(env); + if (!result) { + LOGGER.info(XACMLErrorConstants.ERROR_PERMISSIONS + " invalid Environment Header"); + return result; + } + // decode the user/pwd from the request header + String[] userNamePass = getUserInfo(authHeader, clientAuthHeader); + try { - String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); - if (userNamePass == null || userNamePass.length == 0) { - String usernameAndPassword = null; - byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - String username = tokenizer.nextToken(); - String password = tokenizer.nextToken(); - userNamePass = new String[] {username, password}; - } - LOGGER.info("User " + userNamePass[0] + " is Accessing Policy Engine API."); - Boolean result = false; // Check Backward Compatibility. - try { - /* - * If AAF is NOT enabled in the properties we will allow the user to continue to use the - * client.properties file to authenticate. Note: Disabling AAF is for testing purposes and not intended - * for production. - */ - if ("false".equals(XACMLProperties.getProperty("enable_aaf"))) { - result = clientAuth(userNamePass); - } - } catch (Exception e) { - LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + request.setAttribute("Mechid", ""); + result = false; + /* + * If AAF is NOT enabled in the properties we will allow the user to continue to use the client.properties + * file to authenticate. Note: Disabling AAF is for testing purposes and not intended for production. + */ + if ("false".equals(XACMLProperties.getProperty("enable_aaf"))) { + result = clientAuth(userNamePass); } if (!result) { - String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace"); - String aafResource = XACMLProperties.getProperty("policy.aaf.root.permission"); - String type = null; - if (!userNamePass[0].contains("@") && aafPolicyNameSpace != null) { - userNamePass[0] = userNamePass[0] + "@" + reverseNamespace(aafPolicyNameSpace); - } else { - LOGGER.info("No AAF NameSpace specified in properties"); - } - if (aafResource != null) { - type = aafResource + "." + resource; - } else { - LOGGER.warn("No AAF Resource specified in properties"); - return false; - } - LOGGER.info("Contacting AAF in : " + environment); - result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], type, environment, "*"); + result = aafAuth(userNamePass, resource); + request.setAttribute("Mechid", userNamePass[0]); + } + } catch (Exception e) { + LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + result = false; + } + return result; + + } + + private static boolean checkEnv(String env) { + if (StringUtils.isBlank(env)) { + // must be old type of req + return true; + } else { + return env.trim().equalsIgnoreCase(getEnvironment()); + } + + } + + private static boolean aafAuth(String[] userNamePass, String resource) { + boolean result = false; + String permission = getPermission(resource); + try { + String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace"); + if (!userNamePass[0].contains("@") && aafPolicyNameSpace != null) { + userNamePass[0] = userNamePass[0] + "@" + reverseNamespace(aafPolicyNameSpace); + } else { + LOGGER.info("No AAF NameSpace specified in properties"); } + + LOGGER.info("Contacting AAF in : " + environment); + result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], permission, environment, "*"); + return result; } catch (Exception e) { LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); @@ -140,6 +170,33 @@ public class PDPApiAuth { } } + private static String getPermission(String resource) { + String aafResource = XACMLProperties.getProperty("policy.aaf.root.permission"); + String perm = resource; + if (StringUtils.containsIgnoreCase(perm, "Notification")) { + perm = "notification"; + } else if (StringUtils.containsIgnoreCase(perm, "heartbeat")) { + perm = "notification"; + } else if (StringUtils.containsIgnoreCase(perm, "createDictionary")) { + perm = "createDictionary"; + } else if (StringUtils.containsIgnoreCase(perm, "updateDictionary")) { + perm = "updateDictionary"; + } else if (StringUtils.containsIgnoreCase(perm, "getDictionary")) { + perm = "getDictionary"; + } else if (StringUtils.containsIgnoreCase(perm, "create")) { + perm = "createPolicy"; + } else if (StringUtils.containsIgnoreCase(perm, "update")) { + perm = "updatePolicy"; + } + + if (!StringUtils.isBlank(aafResource)) { + perm = aafResource + "." + perm; + } else { + LOGGER.info("No AAF Resource specified in properties"); + } + return perm; + } + private static Boolean clientAuth(String[] userNamePass) { if (clientPath == null) { setProperty(); @@ -161,23 +218,16 @@ public class PDPApiAuth { return false; } - private static String reverseNamespace(String namespace) { - final List<String> components = Arrays.asList(namespace.split("\\.")); - Collections.reverse(components); - return String.join(".", components); - } - private static Map<String, ArrayList<String>> readProps(Path clientPath) throws PolicyEngineException { if (oldModified != null) { Long newModified = clientPath.toFile().lastModified(); - if (newModified == oldModified) { + if (oldModified.equals(newModified)) { return clientMap; } } - InputStream in; + Properties clientProp = new Properties(); - try { - in = new FileInputStream(clientPath.toFile()); + try (InputStream in = new FileInputStream(clientPath.toFile())) { clientProp.load(in); } catch (IOException e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR, e); @@ -188,14 +238,13 @@ public class PDPApiAuth { clientMap = new HashMap<>(); // for (Object propKey : clientProp.keySet()) { - String clientID = (String) propKey; - String clientValue = clientProp.getProperty(clientID); + String clientId = (String) propKey; + String clientValue = clientProp.getProperty(clientId); if (clientValue != null && clientValue.contains(",")) { ArrayList<String> clientValues = new ArrayList<>(Arrays.asList(clientValue.split("\\s*,\\s*"))); - if (clientValues.get(0) != null || clientValues.get(1) != null || clientValues.get(0).isEmpty() - || clientValues.get(1).isEmpty()) { + if (!StringUtils.isBlank(clientValues.get(0))) { clientValues.set(0, PeCryptoUtils.decrypt(clientValues.get(0))); - clientMap.put(clientID, clientValues); + clientMap.put(clientId, clientValues); } } } @@ -207,4 +256,32 @@ public class PDPApiAuth { oldModified = clientPath.toFile().lastModified(); return clientMap; } + + private static String[] getUserInfo(final String authHeader, final String clientAuthHeader) { + String userInfo = authHeader; + if (!StringUtils.isBlank(clientAuthHeader)) { + userInfo = clientAuthHeader; + } + + String[] userNamePass = null; + + try { + userNamePass = PolicyUtils.decodeBasicEncoding(userInfo); + if (userNamePass == null || userNamePass.length == 0) { + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(userInfo); + usernameAndPassword = new String(decodedBytes, StandardCharsets.UTF_8); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + userNamePass = new String[] {username, password}; + } + LOGGER.info("User " + userNamePass[0] + " is Accessing Policy Engine API - "); + } catch (Exception e) { + LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + return new String[0]; + } + return userNamePass; + } + } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/PdpAuthenticationFilter.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/PdpAuthenticationFilter.java new file mode 100644 index 000000000..b573b2e10 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/PdpAuthenticationFilter.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.rest.restauth; + +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Servlet Filter implementation class PdpAuthenticationFilter. + */ +@WebFilter("/*") +public class PdpAuthenticationFilter implements Filter { + private static final String APISTR = "/api/"; + public static final String AUTHENTICATION_HEADER = "Authorization"; + public static final String ENVIRONMENT_HEADER = "Environment"; + public static final String CLIENTAUTH_HEADER = "ClientAuth"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) + throws IOException, ServletException { + if (!(request instanceof HttpServletRequest)) { + return; + } + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); + String authHeader = httpServletRequest.getHeader(AUTHENTICATION_HEADER); + String clientAuthHeader = httpServletRequest.getHeader(CLIENTAUTH_HEADER); + String path = ((HttpServletRequest) request).getRequestURI(); + String resource = path.substring(path.lastIndexOf('/') + 1); + + boolean authenticationStatus = + AuthenticationService.checkPermissions(clientAuthHeader, authHeader, resource, environment, request); + + if (authenticationStatus) { + if (check(path)) { + path = path.substring(path.indexOf('/', 1)); + if (!path.contains(APISTR)) { + request.getRequestDispatcher(APISTR + path).forward(request, response); + } else { + request.getRequestDispatcher(path).forward(request, response); + } + + } else { + filter.doFilter(request, response); + } + } else if (path.contains("swagger") || path.contains("api-docs") || path.contains("configuration") + || path.contains("count")) { + path = path.substring(path.indexOf('/', 1) + 1); + request.getRequestDispatcher(APISTR + path).forward(request, response); + } else if (path.contains("notifications")) { + filter.doFilter(request, response); + } else { + if (response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } + } + + private boolean check(String path) { + return !(path.endsWith("/pdp/") || path.endsWith("/pdp") || path.endsWith("/test")); + } + + @Override + public void destroy() { + // Do nothing. + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + // Do nothing. + } + +} |