Auditing User Operations Push or Delete Policies.
[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.URL;
40 import java.net.URLEncoder;
41 import java.nio.charset.StandardCharsets;
42 import java.util.Arrays;
43 import java.util.Base64;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.Map;
47 import java.util.Set;
48 import org.apache.commons.io.IOUtils;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.rest.XACMLRestProperties;
52 import org.onap.policy.rest.adapter.PolicyRestAdapter;
53 import org.onap.policy.utils.PeCryptoUtils;
54 import org.onap.policy.xacml.api.XACMLErrorConstants;
55 import org.onap.policy.xacml.api.pap.OnapPDP;
56 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
57 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
58 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
59 import org.onap.policy.xacml.std.pap.StdPDP;
60 import org.onap.policy.xacml.std.pap.StdPDPGroup;
61 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
62 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
63 import org.onap.policy.xacml.std.pap.StdPDPStatus;
64
65 /**
66  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
67  * interface
68  *
69  *
70  */
71 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
72     private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
73
74     private static final String GROUP_ID = "groupId=";
75
76     //
77     // URL of the PAP Servlet that this Admin Console talks to
78     //
79     private String papServletURLString;
80
81     /**
82      * Set up link with PAP Servlet and get our initial set of Groups
83      *
84      * @throws PAPException When failing to register with PAP
85      */
86     public RESTfulPAPEngine(String myURLString) throws PAPException {
87         //
88         // Get our URL to the PAP servlet
89         //
90         this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
91         if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
92             String message =
93                     "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation.  Admin Console cannot call PAP.";
94             LOGGER.error(message);
95             throw new PAPException(message);
96         }
97
98         //
99         // register this Admin Console with the PAP Servlet to get updates
100         //
101         Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
102         if (newURL != null) {
103             // assume this was a re-direct and try again
104             LOGGER.warn("Redirecting to '" + newURL + "'");
105             this.papServletURLString = (String) newURL;
106             newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
107             if (newURL != null) {
108                 LOGGER.error("Failed to redirect to " + this.papServletURLString);
109                 throw new PAPException("Failed to register with PAP");
110             }
111         }
112     }
113
114     //
115     // High-level commands used by the Admin Console code through the PAPEngine Interface
116     //
117
118     @Override
119     public OnapPDPGroup getDefaultGroup() throws PAPException {
120         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
121     }
122
123     @Override
124     public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
125         sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
126     }
127
128     @SuppressWarnings("unchecked")
129     @Override
130     public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
131         Set<OnapPDPGroup> newGroupSet;
132         newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
133         return Collections.unmodifiableSet(newGroupSet);
134     }
135
136     @Override
137     public OnapPDPGroup getGroup(String id) throws PAPException {
138         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
139     }
140
141     @Override
142     public void newGroup(String name, String description) throws PAPException {
143         String escapedName;
144         String escapedDescription;
145         try {
146             escapedName = URLEncoder.encode(name, "UTF-8");
147             escapedDescription = URLEncoder.encode(description, "UTF-8");
148         } catch (UnsupportedEncodingException e) {
149             throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() + e);
150         }
151
152         this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
153                 "groupDescription=" + escapedDescription);
154     }
155
156     /**
157      * Update the configuration on the PAP for a single Group.
158      *
159      * @param group
160      * @return
161      * @throws PAPException
162      */
163     @Override
164     public void updateGroup(OnapPDPGroup group) throws PAPException {
165         try {
166             //
167             // ASSUME that all of the policies mentioned in this group are already located in the correct directory on
168             // the PAP!
169             //
170             // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the
171             // Workspace.
172             //
173             // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
174             // This is not efficient since most of the policies will already exist there.
175             // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any
176             // corrupted files on the PAP get refreshed.
177             // now update the group object on the PAP
178             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
179         } catch (Exception e) {
180             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
181             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
182             throw new PAPException(message);
183         }
184     }
185
186     /*
187      * Passing UserName to PAP Rest for Audit Logging.
188      *
189      * @see org.onap.policy.xacml.api.pap.PAPPolicyEngine#updateGroup(org.onap.policy.xacml.api.pap.OnapPDPGroup,
190      * java.lang.String)
191      */
192     @Override
193     public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
194         try {
195             sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
196         } catch (Exception e) {
197             String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
198             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
199             throw new PAPException(message);
200         }
201     }
202
203     @Override
204     public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
205         String moveToGroupString = null;
206         if (newGroup != null) {
207             moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
208         }
209         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
210     }
211
212     @Override
213     public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
214         return getPDPGroup(pdp.getId());
215     }
216
217     public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
218         return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
219                 "getPDPGroup=");
220     }
221
222     @Override
223     public OnapPDP getPDP(String pdpId) throws PAPException {
224         return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
225     }
226
227     @Override
228     public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
229             throws PAPException {
230         StdPDP newPDP = new StdPDP(id, name, description, jmxport);
231         sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
232     }
233
234     @Override
235     public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
236         sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
237     }
238
239     @Override
240     public void updatePDP(OnapPDP pdp) throws PAPException {
241         OnapPDPGroup group = getPDPGroup(pdp);
242         sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
243     }
244
245     @Override
246     public void removePDP(OnapPDP pdp) throws PAPException {
247         OnapPDPGroup group = getPDPGroup(pdp);
248         sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
249     }
250
251     // Validate the Policy Data
252     public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
253         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
254                 policyAdapter.getConfigType(), "Base");
255
256         // send JSON object to PAP
257         return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
258                 "policyType=" + policyType);
259     }
260
261
262
263     @Override
264     public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group)
265             throws PAPException {
266         // copy the (one) file into the target directory on the PAP servlet
267         copyFile(id, group, policy);
268
269         // adjust the local copy of the group to include the new policy
270         PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
271         group.getPolicies().add(pdpPolicy);
272
273         // tell the PAP servlet to include the policy in the configuration
274         updateGroup(group);
275     }
276
277     /**
278      * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
279      * exception.
280      *
281      * @param policyId
282      * @param group
283      * @param policy
284      * @return
285      * @throws PAPException
286      */
287     public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
288         // send the policy file to the PAP Servlet
289         try {
290             sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
291         } catch (Exception e) {
292             String message = "Unable to PUT policy '" + policyId + "', e:" + e;
293             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
294             throw new PAPException(message);
295         }
296     }
297
298     @Override
299     public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
300         if (policy == null || group == null) {
301             throw new PAPException("Null input policy=" + policy + "  group=" + group);
302         }
303         try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
304             copyFile(policy.getId(), group, is);
305         } catch (Exception e) {
306             String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
307             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
308             throw new PAPException(message);
309         }
310     }
311
312     @Override
313     public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
314         throw new PAPException("NOT IMPLEMENTED");
315     }
316
317     /**
318      * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
319      * status info.
320      *
321      * @param pdp
322      * @return
323      * @throws PAPException
324      */
325     @Override
326     public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
327         return (StdPDPStatus) sendToPAP("GET", pdp, null, StdPDPStatus.class);
328     }
329
330     //
331     // Internal Operations called by the PAPEngine Interface methods
332     //
333
334     /**
335      * Send a request to the PAP Servlet and get the response.
336      *
337      * The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be
338      * encoded into JSON and pushed into the Request OutputStream.
339      *
340      * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
341      *
342      * @param method
343      * @param content - EITHER an InputStream OR an Object to be encoded in JSON
344      * @param collectionTypeClass
345      * @param responseContentClass
346      * @param parameters
347      * @return
348      * @throws PAPException
349      */
350     @SuppressWarnings({"rawtypes", "unchecked"})
351     private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
352             String... parameters) throws PAPException {
353         HttpURLConnection connection = null;
354         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
355         LOGGER.info("User Id is " + papID);
356         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
357         String papPass = PeCryptoUtils
358                 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
359         Base64.Encoder encoder = Base64.getEncoder();
360         String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
361         Object contentObj = content;
362         LOGGER.info("Encoding for the PAP is: " + encoding);
363         try {
364             String fullURL = papServletURLString;
365             if (parameters != null && parameters.length > 0) {
366                 StringBuilder queryString = new StringBuilder();
367                 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
368                 fullURL += "?" + queryString.substring(1);
369             }
370
371             // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
372             if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
373                 // Adjust the url and properties appropriately
374                 String pdpID = ((OnapPDP) contentObj).getId();
375                 fullURL = pdpID + "?type=Status";
376                 contentObj = null;
377                 if (CheckPDP.validateID(pdpID)) {
378                     encoding = CheckPDP.getEncoding(pdpID);
379                 }
380             }
381
382             URL url = new URL(fullURL);
383
384             //
385             // Open up the connection
386             //
387             connection = (HttpURLConnection) url.openConnection();
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 }