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