Merge "Remove powermock to increase coverage"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / RESTfulPAPEngine.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Bell Canada
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.admin;
24
25 import com.att.research.xacml.api.pap.PAPException;
26 import com.att.research.xacml.api.pap.PDPPolicy;
27 import com.att.research.xacml.api.pap.PDPStatus;
28 import com.att.research.xacml.util.XACMLProperties;
29 import com.fasterxml.jackson.databind.DeserializationFeature;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.type.CollectionType;
32 import java.io.File;
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.UnsupportedEncodingException;
38 import java.net.HttpURLConnection;
39 import java.net.MalformedURLException;
40 import java.net.URL;
41 import java.net.URLConnection;
42 import java.net.URLEncoder;
43 import java.nio.charset.StandardCharsets;
44 import java.util.Arrays;
45 import java.util.Base64;
46 import java.util.Collections;
47 import java.util.HashMap;
48 import java.util.Map;
49 import java.util.Set;
50 import org.apache.commons.io.IOUtils;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.rest.XACMLRestProperties;
54 import org.onap.policy.rest.adapter.PolicyRestAdapter;
55 import org.onap.policy.utils.PeCryptoUtils;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.OnapPDP;
58 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
59 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
60 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
61 import org.onap.policy.xacml.std.pap.StdPDP;
62 import org.onap.policy.xacml.std.pap.StdPDPGroup;
63 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
64 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
65 import org.onap.policy.xacml.std.pap.StdPDPStatus;
66
67 /**
68  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
69  * interface
70  *
71  *
72  */
73 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
74     private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
75
76     private static final String GROUP_ID = "groupId=";
77
78     //
79     // URL of the PAP Servlet that this Admin Console talks to
80     //
81     private String papServletURLString;
82
83     /**
84      * Set up link with PAP Servlet and get our initial set of Groups
85      *
86      * @throws PAPException When failing to register with PAP
87      */
88     public RESTfulPAPEngine(String myURLString) throws PAPException {
89         //
90         // Get our URL to the PAP servlet
91         //
92         this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
93         if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
94             String message =
95                     "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation.  Admin Console cannot call PAP.";
96             LOGGER.error(message);
97             throw new PAPException(message);
98         }
99
100         //
101         // register this Admin Console with the PAP Servlet to get updates
102         //
103         Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
104         if (newURL != null) {
105             // assume this was a re-direct and try again
106             LOGGER.warn("Redirecting to '" + newURL + "'");
107             this.papServletURLString = (String) newURL;
108             newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
109             if (newURL != null) {
110                 LOGGER.error("Failed to redirect to " + this.papServletURLString);
111                 throw new PAPException("Failed to register with PAP");
112             }
113         }
114     }
115
116     //
117     // High-level commands used by the Admin Console code through the PAPEngine Interface
118     //
119
120     @Override
121     public OnapPDPGroup getDefaultGroup() throws PAPException {
122         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
123     }
124
125     @Override
126     public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
127         sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
128     }
129
130     @SuppressWarnings("unchecked")
131     @Override
132     public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
133         Set<OnapPDPGroup> newGroupSet;
134         newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
135         return Collections.unmodifiableSet(newGroupSet);
136     }
137
138     @Override
139     public OnapPDPGroup getGroup(String id) throws PAPException {
140         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
141     }
142
143     @Override
144     public void newGroup(String name, String description) throws PAPException {
145         String escapedName;
146         String escapedDescription;
147         try {
148             escapedName = URLEncoder.encode(name, "UTF-8");
149             escapedDescription = URLEncoder.encode(description, "UTF-8");
150         } catch (UnsupportedEncodingException e) {
151             throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() + e);
152         }
153
154         this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
155                 "groupDescription=" + escapedDescription);
156     }
157
158     /**
159      * Update the configuration on the PAP for a single Group.
160      *
161      * @param group
162      * @return
163      * @throws PAPException
164      */
165     @Override
166     public void updateGroup(OnapPDPGroup group) throws PAPException {
167         try {
168             //
169             // ASSUME that all of the policies mentioned in this group are already located in the correct directory on
170             // the PAP!
171             //
172             // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the
173             // Workspace.
174             //
175             // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
176             // This is not efficient since most of the policies will already exist there.
177             // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any
178             // corrupted files on the PAP get refreshed.
179             // now update the group object on the PAP
180             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
181         } catch (Exception e) {
182             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
183             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
184             throw new PAPException(message);
185         }
186     }
187
188     /*
189      * Passing UserName to PAP Rest for Audit Logging.
190      *
191      * @see org.onap.policy.xacml.api.pap.PAPPolicyEngine#updateGroup(org.onap.policy.xacml.api.pap.OnapPDPGroup,
192      * java.lang.String)
193      */
194     @Override
195     public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
196         try {
197             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
198         } catch (Exception e) {
199             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
200             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
201             throw new PAPException(message);
202         }
203     }
204
205     @Override
206     public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
207         String moveToGroupString = null;
208         if (newGroup != null) {
209             moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
210         }
211         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
212     }
213
214     @Override
215     public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
216         return getPDPGroup(pdp.getId());
217     }
218
219     public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
220         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
221                 "getPDPGroup=");
222     }
223
224     @Override
225     public OnapPDP getPDP(String pdpId) throws PAPException {
226         return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
227     }
228
229     @Override
230     public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
231             throws PAPException {
232         StdPDP newPDP = new StdPDP(id, name, description, jmxport);
233         sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
234     }
235
236     @Override
237     public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
238         sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
239     }
240
241     @Override
242     public void updatePDP(OnapPDP pdp) throws PAPException {
243         OnapPDPGroup group = getPDPGroup(pdp);
244         sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
245     }
246
247     @Override
248     public void removePDP(OnapPDP pdp) throws PAPException {
249         OnapPDPGroup group = getPDPGroup(pdp);
250         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
251     }
252
253     // Validate the Policy Data
254     public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
255         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
256                 policyAdapter.getConfigType(), "Base");
257
258         // send JSON object to PAP
259         return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
260                 "policyType=" + policyType);
261     }
262
263
264
265     @Override
266     public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group)
267             throws PAPException {
268         // copy the (one) file into the target directory on the PAP servlet
269         copyFile(id, group, policy);
270
271         // adjust the local copy of the group to include the new policy
272         PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
273         group.getPolicies().add(pdpPolicy);
274
275         // tell the PAP servlet to include the policy in the configuration
276         updateGroup(group);
277     }
278
279     /**
280      * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
281      * exception.
282      *
283      * @param policyId
284      * @param group
285      * @param policy
286      * @return
287      * @throws PAPException
288      */
289     public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
290         // send the policy file to the PAP Servlet
291         try {
292             sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
293         } catch (Exception e) {
294             String message = "Unable to PUT policy '" + policyId + "', e:" + e;
295             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
296             throw new PAPException(message);
297         }
298     }
299
300     @Override
301     public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
302         if (policy == null || group == null) {
303             throw new PAPException("Null input policy=" + policy + "  group=" + group);
304         }
305         try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
306             copyFile(policy.getId(), group, is);
307         } catch (Exception e) {
308             String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
309             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
310             throw new PAPException(message);
311         }
312     }
313
314     @Override
315     public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
316         throw new PAPException("NOT IMPLEMENTED");
317     }
318
319     /**
320      * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
321      * status info.
322      *
323      * @param pdp
324      * @return
325      * @throws PAPException
326      */
327     @Override
328     public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
329         return (StdPDPStatus) sendToPAP("GET", pdp, null, StdPDPStatus.class);
330     }
331
332     //
333     // Internal Operations called by the PAPEngine Interface methods
334     //
335
336     /**
337      * Send a request to the PAP Servlet and get the response.
338      *
339      * The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be
340      * encoded into JSON and pushed into the Request OutputStream.
341      *
342      * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
343      *
344      * @param method
345      * @param content - EITHER an InputStream OR an Object to be encoded in JSON
346      * @param collectionTypeClass
347      * @param responseContentClass
348      * @param parameters
349      * @return
350      * @throws PAPException
351      */
352     @SuppressWarnings({"rawtypes", "unchecked"})
353     private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
354             String... parameters) throws PAPException {
355         HttpURLConnection connection = null;
356         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
357         LOGGER.info("User Id is " + papID);
358         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
359         String papPass = PeCryptoUtils
360                 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
361         Base64.Encoder encoder = Base64.getEncoder();
362         String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
363         Object contentObj = content;
364         LOGGER.info("Encoding for the PAP is: " + encoding);
365         try {
366             String fullURL = papServletURLString;
367             if (parameters != null && parameters.length > 0) {
368                 StringBuilder queryString = new StringBuilder();
369                 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
370                 fullURL += "?" + queryString.substring(1);
371             }
372
373             // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
374             if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
375                 // Adjust the url and properties appropriately
376                 String pdpID = ((OnapPDP) contentObj).getId();
377                 fullURL = pdpID + "?type=Status";
378                 contentObj = null;
379                 if (CheckPDP.validateID(pdpID)) {
380                     encoding = CheckPDP.getEncoding(pdpID);
381                 }
382             }
383
384             //
385             // Open up the connection
386             //
387             connection = (HttpURLConnection) makeConnection(fullURL);
388             //
389             // Setup our method and headers
390             //
391             connection.setRequestMethod(method);
392             connection.setUseCaches(false);
393             //
394             // Adding this in. It seems the HttpUrlConnection class does NOT
395             // properly forward our headers for POST re-direction. It does so
396             // for a GET re-direction.
397             //
398             // So we need to handle this ourselves.
399             //
400             connection.setInstanceFollowRedirects(false);
401             connection.setRequestProperty("Authorization", "Basic " + encoding);
402             connection.setDoOutput(true);
403             connection.setDoInput(true);
404
405             if (contentObj != null) {
406                 if (contentObj instanceof InputStream) {
407                     sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
408                 } else {
409                     // The contentObj is an object to be encoded in JSON
410                     ObjectMapper mapper = new ObjectMapper();
411                     mapper.writeValue(connection.getOutputStream(), contentObj);
412                 }
413             }
414             //
415             // Do the connect
416             //
417             connection.connect();
418             if (connection.getResponseCode() == 204) {
419                 LOGGER.info("Success - no content.");
420                 return null;
421             } else if (connection.getResponseCode() == 200) {
422                 LOGGER.info("Success. We have a return object.");
423                 String isValidData = connection.getHeaderField("isValidData");
424                 String isSuccess = connection.getHeaderField("successMapKey");
425                 Map<String, String> successMap = new HashMap<>();
426                 if ("true".equalsIgnoreCase(isValidData)) {
427                     LOGGER.info("Policy Data is valid.");
428                     return true;
429                 } else if ("false".equalsIgnoreCase(isValidData)) {
430                     LOGGER.info("Policy Data is invalid.");
431                     return false;
432                 } else if ("success".equalsIgnoreCase(isSuccess)) {
433                     LOGGER.info("Policy Created Successfully!");
434                     String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
435                     successMap.put("success", finalPolicyPath);
436                     return successMap;
437                 } else if ("error".equalsIgnoreCase(isSuccess)) {
438                     LOGGER.info("There was an error while creating the policy!");
439                     successMap.put("error", "error");
440                     return successMap;
441                 } else {
442                     // get the response content into a String
443                     String json = getJsonString(connection);
444
445                     // convert Object sent as JSON into local object
446                     ObjectMapper mapper = new ObjectMapper();
447                     mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
448                     if (collectionTypeClass != null) {
449                         // collection of objects expected
450                         final CollectionType javaType = mapper.getTypeFactory()
451                                 .constructCollectionType(collectionTypeClass, responseContentClass);
452                         return mapper.readValue(json, javaType);
453                     } else {
454                         // single value object expected
455                         return mapper.readValue(json, responseContentClass);
456                     }
457                 }
458             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
459                 // redirection
460                 String newURL = connection.getHeaderField("Location");
461                 if (newURL == null) {
462                     LOGGER.error(
463                             "No Location header to redirect to when response code=" + connection.getResponseCode());
464                     throw new IOException(
465                             "No redirect Location header when response code=" + connection.getResponseCode());
466                 }
467                 int qIndex = newURL.indexOf('?');
468                 if (qIndex > 0) {
469                     newURL = newURL.substring(0, qIndex);
470                 }
471                 LOGGER.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
472                 return newURL;
473             } else {
474                 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + "  message: "
475                         + connection.getResponseMessage());
476                 throw new IOException(
477                         "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
478             }
479         } catch (Exception e) {
480             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
481             throw new PAPException("Request/Response threw :" + e);
482         } finally {
483             // cleanup the connection
484             if (connection != null) {
485                 try {
486                     // For some reason trying to get the inputStream from the connection
487                     // throws an exception rather than returning null when the InputStream does not exist.
488                     InputStream is = connection.getInputStream();
489                     if (is != null) {
490                         is.close();
491                     }
492                 } catch (IOException ex) {
493                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
494                 }
495                 connection.disconnect();
496             }
497         }
498     }
499
500     private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
501         try {
502             //
503             // Send our current policy configuration
504             //
505             try (OutputStream os = connection.getOutputStream()) {
506                 int count = IOUtils.copy(contentObj, os);
507                 if (LOGGER.isDebugEnabled()) {
508                     LOGGER.debug("copied to output, bytes=" + count);
509                 }
510             }
511         } catch (Exception e) {
512             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
513         }
514     }
515
516     private String getJsonString(final HttpURLConnection connection) throws IOException {
517         String json;
518         // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
519         try (java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
520             scanner.useDelimiter("\\A");
521             json = scanner.hasNext() ? scanner.next() : "";
522         } catch (Exception e) {
523             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e,
524                     e);
525             throw e;
526         }
527         LOGGER.info("JSON response from PAP: " + json);
528         return json;
529     }
530
531     // these may be overridden by junit tests
532
533     protected URLConnection makeConnection(String fullURL) throws IOException {
534         return new URL(fullURL).openConnection();
535     }
536 }