Fix license on updated engine files
[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.URLConnection;
34 import java.net.URLEncoder;
35 import java.nio.charset.StandardCharsets;
36 import java.util.Arrays;
37 import java.util.Base64;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.Set;
42 import org.apache.commons.io.IOUtils;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.rest.XACMLRestProperties;
46 import org.onap.policy.rest.adapter.PolicyRestAdapter;
47 import org.onap.policy.utils.PeCryptoUtils;
48 import org.onap.policy.xacml.api.XACMLErrorConstants;
49 import org.onap.policy.xacml.api.pap.OnapPDP;
50 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
51 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
52 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
53 import org.onap.policy.xacml.std.pap.StdPDP;
54 import org.onap.policy.xacml.std.pap.StdPDPGroup;
55 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
56 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
57 import org.onap.policy.xacml.std.pap.StdPDPStatus;
58 import com.att.research.xacml.api.pap.PAPException;
59 import com.att.research.xacml.api.pap.PDPPolicy;
60 import com.att.research.xacml.api.pap.PDPStatus;
61 import com.att.research.xacml.util.XACMLProperties;
62 import com.fasterxml.jackson.databind.DeserializationFeature;
63 import com.fasterxml.jackson.databind.ObjectMapper;
64 import com.fasterxml.jackson.databind.type.CollectionType;
65
66 /**
67  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
68  * interface
69  *
70  *
71  */
72 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
73     private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
74
75     private static final String GROUP_ID = "groupId=";
76
77     //
78     // URL of the PAP Servlet that this Admin Console talks to
79     //
80     private String papServletURLString;
81
82     /**
83      * Set up link with PAP Servlet and get our initial set of Groups
84      *
85      * @throws PAPException When failing to register with PAP
86      */
87     public RESTfulPAPEngine(String myURLString) throws PAPException {
88         //
89         // Get our URL to the PAP servlet
90         //
91         this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
92         if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
93             String message =
94                     "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) throws PAPException {
144         String escapedName;
145         String escapedDescription;
146         try {
147             escapedName = URLEncoder.encode(name, "UTF-8");
148             escapedDescription = URLEncoder.encode(description, "UTF-8");
149         } catch (UnsupportedEncodingException e) {
150             throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() + e);
151         }
152
153         this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
154                 "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
169             // the PAP!
170             //
171             // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the
172             // Workspace.
173             //
174             // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
175             // This is not efficient since most of the policies will already exist there.
176             // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any
177             // corrupted files on the PAP get refreshed.
178             // now update the group object on the PAP
179             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
180         } catch (Exception e) {
181             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
182             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
183             throw new PAPException(message);
184         }
185     }
186
187     /*
188      * Passing UserName to PAP Rest for Audit Logging.
189      *
190      * @see org.onap.policy.xacml.api.pap.PAPPolicyEngine#updateGroup(org.onap.policy.xacml.api.pap.OnapPDPGroup,
191      * java.lang.String)
192      */
193     @Override
194     public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
195         try {
196             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
197         } catch (Exception e) {
198             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
199             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
200             throw new PAPException(message);
201         }
202     }
203
204     @Override
205     public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
206         String moveToGroupString = null;
207         if (newGroup != null) {
208             moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
209         }
210         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
211     }
212
213     @Override
214     public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
215         return getPDPGroup(pdp.getId());
216     }
217
218     public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
219         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
220                 "getPDPGroup=");
221     }
222
223     @Override
224     public OnapPDP getPDP(String pdpId) throws PAPException {
225         return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
226     }
227
228     @Override
229     public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
230             throws PAPException {
231         StdPDP newPDP = new StdPDP(id, name, description, jmxport);
232         sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
233     }
234
235     @Override
236     public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
237         sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
238     }
239
240     @Override
241     public void updatePDP(OnapPDP pdp) throws PAPException {
242         OnapPDPGroup group = getPDPGroup(pdp);
243         sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
244     }
245
246     @Override
247     public void removePDP(OnapPDP pdp) throws PAPException {
248         OnapPDPGroup group = getPDPGroup(pdp);
249         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
250     }
251
252     // Validate the Policy Data
253     public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
254         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
255                 policyAdapter.getConfigType(), "Base");
256
257         // send JSON object to PAP
258         return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
259                 "policyType=" + policyType);
260     }
261
262
263
264     @Override
265     public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group)
266             throws PAPException {
267         // copy the (one) file into the target directory on the PAP servlet
268         copyFile(id, group, policy);
269
270         // adjust the local copy of the group to include the new policy
271         PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
272         group.getPolicies().add(pdpPolicy);
273
274         // tell the PAP servlet to include the policy in the configuration
275         updateGroup(group);
276     }
277
278     /**
279      * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
280      * exception.
281      *
282      * @param policyId
283      * @param group
284      * @param policy
285      * @return
286      * @throws PAPException
287      */
288     public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
289         // send the policy file to the PAP Servlet
290         try {
291             sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
292         } catch (Exception e) {
293             String message = "Unable to PUT policy '" + policyId + "', e:" + e;
294             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
295             throw new PAPException(message);
296         }
297     }
298
299     @Override
300     public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
301         if (policy == null || group == null) {
302             throw new PAPException("Null input policy=" + policy + "  group=" + group);
303         }
304         try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
305             copyFile(policy.getId(), group, is);
306         } catch (Exception e) {
307             String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
308             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
309             throw new PAPException(message);
310         }
311     }
312
313     @Override
314     public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
315         throw new PAPException("NOT IMPLEMENTED");
316     }
317
318     /**
319      * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
320      * 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     // Internal Operations called by the PAPEngine Interface methods
333     //
334
335     /**
336      * Send a request to the PAP Servlet and get the response.
337      *
338      * The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be
339      * encoded into JSON and pushed into the Request OutputStream.
340      *
341      * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
342      *
343      * @param method
344      * @param content - EITHER an InputStream OR an Object to be encoded in JSON
345      * @param collectionTypeClass
346      * @param responseContentClass
347      * @param parameters
348      * @return
349      * @throws PAPException
350      */
351     @SuppressWarnings({"rawtypes", "unchecked"})
352     private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
353             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         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
358         String papPass = PeCryptoUtils
359                 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
360         Base64.Encoder encoder = Base64.getEncoder();
361         String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
362         Object contentObj = content;
363         LOGGER.info("Encoding for the PAP is: " + encoding);
364         try {
365             String fullURL = papServletURLString;
366             if (parameters != null && parameters.length > 0) {
367                 StringBuilder queryString = new StringBuilder();
368                 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
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             // Open up the connection
385             //
386             connection = (HttpURLConnection) makeConnection(fullURL);
387             //
388             // Setup our method and headers
389             //
390             connection.setRequestMethod(method);
391             connection.setUseCaches(false);
392             //
393             // Adding this in. It seems the HttpUrlConnection class does NOT
394             // properly forward our headers for POST re-direction. It does so
395             // for a GET re-direction.
396             //
397             // So we need to handle this ourselves.
398             //
399             connection.setInstanceFollowRedirects(false);
400             connection.setRequestProperty("Authorization", "Basic " + encoding);
401             connection.setDoOutput(true);
402             connection.setDoInput(true);
403
404             if (contentObj != null) {
405                 if (contentObj instanceof InputStream) {
406                     sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
407                 } else {
408                     // The contentObj is an object to be encoded in JSON
409                     ObjectMapper mapper = new ObjectMapper();
410                     mapper.writeValue(connection.getOutputStream(), contentObj);
411                 }
412             }
413             //
414             // Do the connect
415             //
416             connection.connect();
417             if (connection.getResponseCode() == 204) {
418                 LOGGER.info("Success - no content.");
419                 return null;
420             } else if (connection.getResponseCode() == 200) {
421                 LOGGER.info("Success. We have a return object.");
422                 String isValidData = connection.getHeaderField("isValidData");
423                 String isSuccess = connection.getHeaderField("successMapKey");
424                 Map<String, String> successMap = new HashMap<>();
425                 if ("true".equalsIgnoreCase(isValidData)) {
426                     LOGGER.info("Policy Data is valid.");
427                     return true;
428                 } else if ("false".equalsIgnoreCase(isValidData)) {
429                     LOGGER.info("Policy Data is invalid.");
430                     return false;
431                 } else if ("success".equalsIgnoreCase(isSuccess)) {
432                     LOGGER.info("Policy Created Successfully!");
433                     String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
434                     successMap.put("success", finalPolicyPath);
435                     return successMap;
436                 } else if ("error".equalsIgnoreCase(isSuccess)) {
437                     LOGGER.info("There was an error while creating the policy!");
438                     successMap.put("error", "error");
439                     return successMap;
440                 } else {
441                     // get the response content into a String
442                     String json = getJsonString(connection);
443
444                     // convert Object sent as JSON into local object
445                     ObjectMapper mapper = new ObjectMapper();
446                     mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
447                     if (collectionTypeClass != null) {
448                         // collection of objects expected
449                         final CollectionType javaType = mapper.getTypeFactory()
450                                 .constructCollectionType(collectionTypeClass, responseContentClass);
451                         return mapper.readValue(json, javaType);
452                     } else {
453                         // single value object expected
454                         return mapper.readValue(json, responseContentClass);
455                     }
456                 }
457             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
458                 // redirection
459                 String newURL = connection.getHeaderField("Location");
460                 if (newURL == null) {
461                     LOGGER.error(
462                             "No Location header to redirect to when response code=" + connection.getResponseCode());
463                     throw new IOException(
464                             "No redirect Location header when response code=" + connection.getResponseCode());
465                 }
466                 int qIndex = newURL.indexOf('?');
467                 if (qIndex > 0) {
468                     newURL = newURL.substring(0, qIndex);
469                 }
470                 LOGGER.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
471                 return newURL;
472             } else {
473                 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + "  message: "
474                         + connection.getResponseMessage());
475                 throw new IOException(
476                         "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
477             }
478         } catch (Exception e) {
479             LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
480             throw new PAPException("Request/Response threw :" + e);
481         } finally {
482             // cleanup the connection
483             if (connection != null) {
484                 try {
485                     // For some reason trying to get the inputStream from the connection
486                     // throws an exception rather than returning null when the InputStream does not exist.
487                     InputStream is = connection.getInputStream();
488                     if (is != null) {
489                         is.close();
490                     }
491                 } catch (IOException ex) {
492                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
493                 }
494                 connection.disconnect();
495             }
496         }
497     }
498
499     private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
500         try {
501             //
502             // Send our current policy configuration
503             //
504             try (OutputStream os = connection.getOutputStream()) {
505                 int count = IOUtils.copy(contentObj, os);
506                 if (LOGGER.isDebugEnabled()) {
507                     LOGGER.debug("copied to output, bytes=" + count);
508                 }
509             }
510         } catch (Exception e) {
511             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
512         }
513     }
514
515     private String getJsonString(final HttpURLConnection connection) throws IOException {
516         String json;
517         // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
518         try (java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
519             scanner.useDelimiter("\\A");
520             json = scanner.hasNext() ? scanner.next() : "";
521         } catch (Exception e) {
522             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e,
523                     e);
524             throw e;
525         }
526         LOGGER.info("JSON response from PAP: " + json);
527         return json;
528     }
529
530     // these may be overridden by junit tests
531
532     protected URLConnection makeConnection(String fullURL) throws IOException {
533         return new URL(fullURL).openConnection();
534     }
535 }