Make clientAuth header optional and log request
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / DeletePolicyService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.rest.api.services;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.stream.Collectors;
28 import org.apache.commons.lang3.StringUtils;
29 import org.onap.policy.api.DeletePolicyParameters;
30 import org.onap.policy.api.PolicyException;
31 import org.onap.policy.api.PolicyNameType;
32 import org.onap.policy.common.logging.flexlogger.FlexLogger;
33 import org.onap.policy.common.logging.flexlogger.Logger;
34 import org.onap.policy.xacml.api.XACMLErrorConstants;
35 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
36 import org.onap.policy.xacml.std.pap.StdPAPPolicyParams;
37 import org.springframework.http.HttpStatus;
38
39
40 /**
41  * The Class DeletePolicyService.
42  */
43 public class DeletePolicyService extends PdpApiService {
44
45     private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName());
46     private DeletePolicyParameters deletePolicyParameters = null;
47     private String result = null;
48     private List<PolicyNameType> policyList = new ArrayList<>();
49
50
51     /**
52      * Instantiates a new delete policy service.
53      *
54      * @param deletePolicyParameters the delete policy parameters
55      * @param reqId the request id
56      */
57     public DeletePolicyService(final DeletePolicyParameters deletePolicyParameters, final String reqId) {
58         super();
59         this.deletePolicyParameters = deletePolicyParameters;
60         deletePolicyParameters.setRequestID(populateRequestId(deletePolicyParameters.getRequestID(), reqId));
61         try {
62             run();
63             specialCheck();
64         } catch (final PolicyException e) {
65             LOGGER.error("Unable to process delete policy request for : " + this.deletePolicyParameters
66                     + PRINT_REQUESTID + this.requestId);
67             result = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
68             status = HttpStatus.BAD_REQUEST;
69         }
70     }
71
72     /**
73      * Special check.
74      */
75     private void specialCheck() {
76         if (result == null) {
77             return;
78         }
79         if (result.contains("BAD REQUEST") || result.contains("PE300") || result.contains("PE200")
80                 || result.contains("not exist") || result.contains("Invalid policyName")) {
81             if (result.contains("groupId")) {
82                 status = HttpStatus.NOT_FOUND;
83             } else {
84                 status = HttpStatus.BAD_REQUEST;
85             }
86         } else if (result.contains("locked down")) {
87             status = HttpStatus.ACCEPTED;
88         } else if (result.contains("not Authorized")) {
89             status = HttpStatus.FORBIDDEN;
90         } else if (result.contains("JPAUtils") || result.contains("database")
91                 || result.contains("policy file") || result.contains("unknown")
92                 || result.contains("configuration")) {
93             status = HttpStatus.INTERNAL_SERVER_ERROR;
94         }
95     }
96
97     /**
98      * Run.
99      *
100      * @throws PolicyException the policy exception
101      */
102     private void run() throws PolicyException {
103         // Check Validation.
104         if (!getValidation()) {
105             LOGGER.error(message);
106             throw new PolicyException(message);
107         }
108         // Get Result.
109         try {
110             LOGGER.debug("Processing delete request:  " + deletePolicyParameters.toString() + PRINT_REQUESTID
111                     + this.requestId);
112             status = HttpStatus.OK;
113             result = processResult();
114         } catch (final Exception e) {
115             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
116             status = HttpStatus.BAD_REQUEST;
117             throw new PolicyException(e);
118         }
119     }
120
121     /**
122      * Process result.
123      *
124      * @return the string
125      * @throws PolicyException the policy exception
126      */
127     private String processResult() throws PolicyException {
128         String response = null;
129         String pdpGroup = deletePolicyParameters.getPdpGroup();
130
131         final PAPServices papServices = new PAPServices();
132         if (!populateFullPolicyName(papServices)) {
133             LOGGER.error(message);
134             return message;
135         }
136
137         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
138             // for deleting policies from the API
139             for (PolicyNameType policyData : policyList) {
140                 // validation ensures there will be one delete policy at a time
141                 final StdPAPPolicy deletePapPolicy =
142                         new StdPAPPolicy(StdPAPPolicyParams.builder().policyName(policyData.getFullPolicyName())
143                                 .deleteCondition(deletePolicyParameters.getDeleteCondition().toString()).build());
144                 // send JSON object to PAP
145                 response = (String) papServices.callPAP(deletePapPolicy,
146                         new String[] {"groupId=" + pdpGroup, "apiflag=deletePapApi", "operation=delete"},
147                         deletePolicyParameters.getRequestID(), policyData.getClientScope());
148             }
149         } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
150             String policies =
151                     policyList.stream().map(PolicyNameType::getFullPolicyName).collect(Collectors.joining(","));
152             // send JSON object to PAP
153             response =
154                     (String) papServices.callPAP(null,
155                             new String[] {"policyName=" + policies, "groupId=" + pdpGroup, "apiflag=deletePdpApi",
156                                     "operation=delete", "userId=API"},
157                             deletePolicyParameters.getRequestID(), clientScope);
158         } else {
159             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist."
160                     + "Please enter either PAP or PDP to delete the policy from a specified Policy Component.";
161             LOGGER.warn(message + PRINT_REQUESTID + requestId);
162             response = message;
163         }
164         return response;
165     }
166
167     /**
168      * Populate full policy name.
169      *
170      * @param papServices the pap services
171      * @return true, if successful
172      */
173     private boolean populateFullPolicyName(final PAPServices papServices) {
174         for (PolicyNameType policyData : policyList) {
175             if (policyData.getPolicyName().contains("xml")) {
176                 policyData.setFullPolicyName(policyData.getPolicyName());
177                 continue;
178             }
179
180             final String activeVersion = papServices.getActiveVersion(policyData.getPolicyScope(),
181                     policyData.getFilePrefix(), policyData.getPolicyName(), policyData.getClientScope(),
182                     deletePolicyParameters.getRequestID());
183
184             if ("pe100".equalsIgnoreCase(activeVersion)) {
185                 message = XACMLErrorConstants.ERROR_PERMISSIONS
186                         + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
187                         + "Contact Administrator for this Scope. ";
188                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
189                 return false;
190             } else if ("pe300".equalsIgnoreCase(activeVersion)) {
191                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
192                         + "This indicates a problem with getting the version"
193                         + "from the PAP or the policy does not exist.";
194                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
195                 return false;
196             }
197             if ("0".equalsIgnoreCase(activeVersion)) {
198                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy."
199                         + "This indicates the policy does not exist, please verify the policy exists.";
200                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
201                 return false;
202             }
203
204             policyData.setFullPolicyName(policyData.getPolicyScope() + "." + policyData.getFilePrefix()
205                     + policyData.getPolicyName() + "." + activeVersion + ".xml");
206         }
207         return true;
208     }
209
210     /**
211      * Gets the validation.
212      *
213      * @return the validation
214      */
215     private boolean getValidation() {
216         if (StringUtils.isBlank(deletePolicyParameters.getPolicyName())) {
217             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
218             return false;
219         }
220
221         String policyType = deletePolicyParameters.getPolicyType();
222         if (StringUtils.isBlank(policyType)) {
223             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
224             return false;
225         }
226
227         if (StringUtils.isBlank(deletePolicyParameters.getPolicyComponent())) {
228             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.";
229             return false;
230         }
231
232         List<String> policyNames = Arrays.asList(deletePolicyParameters.getPolicyName().split(","));
233         List<String> policyTypes = Arrays.asList(deletePolicyParameters.getPolicyType().split(","));
234
235         if (policyTypes.size() > 1 && (policyNames.size() != policyTypes.size())) {
236             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid number of PolicyTypes";
237             return false;
238         }
239
240         if ((policyNames.stream().anyMatch(StringUtils::isBlank))
241                 || (policyTypes.stream().anyMatch(StringUtils::isBlank))) {
242             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid PolicyName or PolicyType";
243             return false;
244         }
245
246         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent()) && policyNames.size() > 1) {
247             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Only one policy can be deleted from PAP at a time";
248             return false;
249         }
250
251         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())
252                 && (deletePolicyParameters.getDeleteCondition() == null
253                         || deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty())) {
254             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
255             LOGGER.warn(message + PRINT_REQUESTID + requestId);
256             return false;
257         }
258
259         if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())
260                 && StringUtils.isBlank(deletePolicyParameters.getPdpGroup())) {
261             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
262             LOGGER.warn(message + PRINT_REQUESTID + requestId);
263             return false;
264         }
265
266         if (!validatePolicyNameAndScope(policyNames, policyTypes, policyList)) {
267             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed validation in validatePolicyNameAndScope - "
268                     + message + PRINT_REQUESTID + requestId);
269             return false;
270         }
271
272         return true;
273     }
274
275     public String getResult() {
276         return result;
277     }
278 }