Add modified copyright notice
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified 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.admin;
23
24
25
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.io.UnsupportedEncodingException;
32 import java.net.HttpURLConnection;
33 import java.net.URL;
34 import java.net.URLEncoder;
35 import java.nio.charset.StandardCharsets;
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.CryptoUtils;
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 groupID = "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 Exception
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     //
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, groupID, "default=");
123     }
124
125     @Override
126     public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
127         sendToPAP("POST", null, null, null, groupID + 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, groupID);
135         return Collections.unmodifiableSet(newGroupSet);
136     }
137
138
139     @Override
140     public OnapPDPGroup getGroup(String id) throws PAPException {
141         return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
142     }
143
144     @Override
145     public void newGroup(String name, String description)
146             throws PAPException {
147         String escapedName = null;
148         String escapedDescription = null;
149         try {
150             escapedName = URLEncoder.encode(name, "UTF-8");
151             escapedDescription = URLEncoder.encode(description, "UTF-8");
152         } catch (UnsupportedEncodingException e) {
153             throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()  +e);
154         }
155
156         this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
157     }
158
159
160     /**
161      * Update the configuration on the PAP for a single Group.
162      *
163      * @param group
164      * @return
165      * @throws PAPException
166      */
167     @Override
168     public void updateGroup(OnapPDPGroup group) throws PAPException {
169
170         try {
171
172             //
173             // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
174             //
175             // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
176             //
177
178
179             // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
180             // This is not efficient since most of the policies will already exist there.
181             // 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.
182
183
184             // now update the group object on the PAP
185
186             sendToPAP("PUT", group, null, null, groupID + group.getId());
187         } catch (Exception e) {
188             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
189             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
190             throw new PAPException(message);
191         }
192     }
193
194
195     @Override
196     public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
197             throws PAPException {
198         String moveToGroupString = null;
199         if (newGroup != null) {
200             moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
201         }
202         sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
203     }
204
205     @Override
206     public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
207         return getPDPGroup(pdp.getId());
208     }
209
210
211     public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
212         return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
213     }
214
215     @Override
216     public OnapPDP getPDP(String pdpId) throws PAPException {
217         return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
218     }
219
220     @Override
221     public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException {
222         StdPDP newPDP = new StdPDP(id, name, description, jmxport);
223         sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
224         return;
225     }
226
227     @Override
228     public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
229         sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
230         return;
231     }
232
233     @Override
234     public void updatePDP(OnapPDP pdp) throws PAPException {
235         OnapPDPGroup group = getPDPGroup(pdp);
236         sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
237         return;
238     }
239
240     @Override
241     public void removePDP(OnapPDP pdp) throws PAPException {
242         OnapPDPGroup group = getPDPGroup(pdp);
243         sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
244         return;
245     }
246
247     //Validate the Policy Data
248     public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
249         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
250
251         //send JSON object to PAP
252         return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
253     }
254
255
256
257     @Override
258     public void publishPolicy(String id, String name, boolean isRoot,
259             InputStream policy, OnapPDPGroup group) throws PAPException {
260
261
262         // copy the (one) file into the target directory on the PAP servlet
263         copyFile(id, group, policy);
264
265         // adjust the local copy of the group to include the new policy
266         PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
267         group.getPolicies().add(pdpPolicy);
268
269         // tell the PAP servlet to include the policy in the configuration
270         updateGroup(group);
271
272         return;
273     }
274
275     /**
276      * Copy a single Policy file from the input stream to the PAP Servlet.
277      * Either this works (silently) or it throws an exception.
278      *
279      * @param policyId
280      * @param group
281      * @param policy
282      * @return
283      * @throws PAPException
284      */
285     public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
286         // send the policy file to the PAP Servlet
287         try {
288             sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
289         } catch (Exception e) {
290             String message = "Unable to PUT policy '" + policyId + "', e:" + e;
291             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
292             throw new PAPException(message);
293         }
294     }
295
296
297     @Override
298     public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
299         if (policy == null || group == null) {
300             throw new PAPException("Null input policy="+policy+"  group="+group);
301         }
302         try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
303             copyFile(policy.getId(), group, is );
304         } catch (Exception e) {
305             String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
306             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
307             throw new PAPException(message);
308         }
309     }
310
311     @Override
312     public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
313         throw new PAPException("NOT IMPLEMENTED");
314
315     }
316
317
318     /**
319      * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
320      * to get detailed status info.
321      *
322      * @param pdp
323      * @return
324      * @throws PAPException
325      */
326     @Override
327     public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
328         return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
329     }
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
340      *  OR it is an object that is to be 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 Exception
351      */
352     @SuppressWarnings({ "rawtypes", "unchecked" })
353     private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
354         HttpURLConnection connection = null;
355         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
356         LOGGER.info("User Id is " + papID);
357         String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
358         Base64.Encoder encoder = Base64.getEncoder();
359         String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
360         Object contentObj = content;
361         LOGGER.info("Encoding for the PAP is: " + encoding);
362         try {
363             String fullURL = papServletURLString;
364             if (parameters != null && parameters.length > 0) {
365                 StringBuilder queryString = new StringBuilder();
366                 for (String p : parameters) {
367                     queryString.append("&" + p);
368                 }
369                 fullURL += "?" + queryString.substring(1);
370             }
371
372             // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
373             if ("GET".equals(method) && (contentObj instanceof OnapPDP) &&      responseContentClass == StdPDPStatus.class) {
374                 // Adjust the url and properties appropriately
375                 String pdpID =((OnapPDP)contentObj).getId();
376                 fullURL = pdpID + "?type=Status";
377                 contentObj = null;
378                 if(CheckPDP.validateID(pdpID)){
379                     encoding = CheckPDP.getEncoding(pdpID);
380                 }
381             }
382
383
384             URL url = new URL(fullURL);
385
386             //
387             // Open up the connection
388             //
389             connection = (HttpURLConnection)url.openConnection();
390             //
391             // Setup our method and headers
392             //
393             connection.setRequestMethod(method);
394             connection.setUseCaches(false);
395             //
396             // Adding this in. It seems the HttpUrlConnection class does NOT
397             // properly forward our headers for POST re-direction. It does so
398             // for a GET re-direction.
399             //
400             // So we need to handle this ourselves.
401             //
402             connection.setInstanceFollowRedirects(false);
403             connection.setRequestProperty("Authorization", "Basic " + encoding);
404             connection.setDoOutput(true);
405             connection.setDoInput(true);
406
407             if (contentObj != null) {
408                 if (contentObj instanceof InputStream) {
409                     sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
410                 } else {
411                     // The contentObj is an object to be encoded in JSON
412                     ObjectMapper mapper = new ObjectMapper();
413                     mapper.writeValue(connection.getOutputStream(),  contentObj);
414                 }
415             }
416             //
417             // Do the connect
418             //
419             connection.connect();
420             if (connection.getResponseCode() == 204) {
421                 LOGGER.info("Success - no content.");
422                 return null;
423             } else if (connection.getResponseCode() == 200) {
424                 LOGGER.info("Success. We have a return object.");
425                 String isValidData = connection.getHeaderField("isValidData");
426                 String isSuccess = connection.getHeaderField("successMapKey");
427                 Map<String, String> successMap = new HashMap<>();
428         if (isValidData != null && "true".equalsIgnoreCase(isValidData)){
429                     LOGGER.info("Policy Data is valid.");
430                     return true;
431         } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) {
432                     LOGGER.info("Policy Data is invalid.");
433                     return false;
434         } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) {
435                     LOGGER.info("Policy Created Successfully!" );
436                     String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
437                     successMap.put("success", finalPolicyPath);
438                     return successMap;
439         } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) {
440                     LOGGER.info("There was an error while creating the policy!");
441                     successMap.put("error", "error");
442                     return successMap;
443                 } else {
444                     // get the response content into a String
445                     String json = getJsonString(connection);
446
447                     // convert Object sent as JSON into local object
448                     ObjectMapper mapper = new ObjectMapper();
449                     mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
450                     if (collectionTypeClass != null) {
451                         // collection of objects expected
452                         final CollectionType javaType =
453                               mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
454
455                         return mapper.readValue(json, javaType);
456                     } else {
457                         // single value object expected
458                         return mapper.readValue(json, responseContentClass);
459                     }
460                 }
461
462             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode()  <= 399) {
463                 // redirection
464                 String newURL = connection.getHeaderField("Location");
465                 if (newURL == null) {
466                     LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode());
467                     throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
468                 }
469                 int qIndex = newURL.indexOf('?');
470                 if (qIndex > 0) {
471                     newURL = newURL.substring(0, qIndex);
472                 }
473                 LOGGER.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
474                 return newURL;
475             } else {
476                 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
477                 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
478             }
479
480         } catch (Exception e) {
481             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
482             throw new PAPException("Request/Response threw :" + e);
483         } finally {
484             // cleanup the connection
485             if (connection != null) {
486                 try {
487                     // For some reason trying to get the inputStream from the connection
488                     // throws an exception rather than returning null when the InputStream does not exist.
489                     InputStream is = connection.getInputStream();
490                     if (is != null) {
491                         is.close();
492                     }
493                 } catch (IOException ex) {
494                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
495                 }
496                 connection.disconnect();
497             }
498         }
499     }
500
501     private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
502         try {
503             //
504             // Send our current policy configuration
505             //
506             try (OutputStream os = connection.getOutputStream()) {
507             int count = IOUtils.copy(contentObj, os);
508                 if (LOGGER.isDebugEnabled()) {
509                     LOGGER.debug("copied to output, bytes="+count);
510                 }
511             }
512         } catch (Exception e) {
513             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
514         }
515     }
516
517     private String getJsonString(final HttpURLConnection connection) throws IOException {
518         String json = null;
519         // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
520         try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
521             scanner.useDelimiter("\\A");
522             json = scanner.hasNext() ? scanner.next() : "";
523         } catch (Exception e){
524             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e, e);
525             throw e;
526         }
527         LOGGER.info("JSON response from PAP: " + json);
528         return json;
529     }
530 }