Merge "Added Junits to ONAP-PDP-REST"
[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  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.admin;
22
23
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.Base64;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Map;
39 import java.util.Set;
40
41 import org.apache.commons.io.IOUtils;
42 import org.onap.policy.rest.XACMLRestProperties;
43 import org.onap.policy.rest.adapter.PolicyRestAdapter;
44 import org.onap.policy.utils.CryptoUtils;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46 import org.onap.policy.xacml.api.pap.OnapPDP;
47 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
48 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
49 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
50 import org.onap.policy.xacml.std.pap.StdPDP;
51 import org.onap.policy.xacml.std.pap.StdPDPGroup;
52 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
53 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
54 import org.onap.policy.xacml.std.pap.StdPDPStatus;
55
56 import com.att.research.xacml.api.pap.PAPException;
57 import com.att.research.xacml.api.pap.PDPPolicy;
58 import com.att.research.xacml.api.pap.PDPStatus;
59 import com.att.research.xacml.util.XACMLProperties;
60 import com.fasterxml.jackson.databind.DeserializationFeature;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62 import com.fasterxml.jackson.databind.type.CollectionType;
63
64 import org.onap.policy.common.logging.flexlogger.FlexLogger; 
65 import org.onap.policy.common.logging.flexlogger.Logger;
66
67 /**
68  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
69  * through a RESTful interface
70  * 
71  *
72  */
73 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
74         private static final Logger LOGGER      = FlexLogger.getLogger(RESTfulPAPEngine.class);
75         
76         private static final String groupID = "groupId=";
77
78         //
79         // URL of the PAP Servlet that this Admin Console talks to
80         //
81         private String papServletURLString;
82         
83         /**
84          * Set up link with PAP Servlet and get our initial set of Groups
85          * @throws Exception 
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 = "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         //
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, groupID, "default=");
122         }
123
124         @Override
125         public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
126                 sendToPAP("POST", null, null, null, groupID + 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, groupID);
134                 return Collections.unmodifiableSet(newGroupSet);
135         }
136
137
138         @Override
139         public OnapPDPGroup getGroup(String id) throws PAPException {
140                 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
141         }
142
143         @Override
144         public void newGroup(String name, String description)
145                         throws PAPException {
146                 String escapedName = null;
147                 String escapedDescription = null;
148                 try {
149                         escapedName = URLEncoder.encode(name, "UTF-8");
150                         escapedDescription = URLEncoder.encode(description, "UTF-8");
151                 } catch (UnsupportedEncodingException e) {
152                         throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()  +e);
153                 }
154                 
155                 this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
156         }
157         
158         
159         /**
160          * Update the configuration on the PAP for a single Group.
161          * 
162          * @param group
163          * @return
164          * @throws PAPException
165          */
166         @Override
167         public void updateGroup(OnapPDPGroup group) throws PAPException {
168
169                 try {
170                         
171                         //
172                         // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
173                         //
174                         // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
175                         // 
176                         
177                         
178                         // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
179                         // This is not efficient since most of the policies will already exist there.
180                         // 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.
181                 
182                         
183                         // now update the group object on the PAP
184                         
185                         sendToPAP("PUT", group, null, null, groupID + group.getId());
186                 } catch (Exception e) {
187                         String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
188                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
189                         throw new PAPException(message);
190                 }
191         }
192         
193         
194         @Override
195         public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
196                         throws PAPException {
197                 String moveToGroupString = null;
198                 if (newGroup != null) {
199                         moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
200                 }
201                 sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
202         }
203         
204         @Override
205         public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
206                 return getPDPGroup(pdp.getId());
207         }
208
209         
210         public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
211                 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
212         }
213
214         @Override
215         public OnapPDP getPDP(String pdpId) throws PAPException {
216                 return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
217         }
218         
219         @Override
220         public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException {
221                 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
222                 sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
223                 return;
224         }
225
226         @Override
227         public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
228                 sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
229                 return;
230         }
231
232         @Override
233         public void updatePDP(OnapPDP pdp) throws PAPException {
234                 OnapPDPGroup group = getPDPGroup(pdp);
235                 sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
236                 return;
237         }
238         
239         @Override
240         public void removePDP(OnapPDP pdp) throws PAPException {
241                 OnapPDPGroup group = getPDPGroup(pdp);
242                 sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
243                 return;
244         }
245         
246         //Validate the Policy Data
247         public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
248                 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
249                 
250                 //send JSON object to PAP
251                 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
252         }
253         
254         
255         
256         @Override
257         public void publishPolicy(String id, String name, boolean isRoot,
258                         InputStream policy, OnapPDPGroup group) throws PAPException {
259                 
260
261                 // copy the (one) file into the target directory on the PAP servlet
262                 copyFile(id, group, policy);
263                 
264                 // adjust the local copy of the group to include the new policy
265                 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
266                 group.getPolicies().add(pdpPolicy);
267                 
268                 // tell the PAP servlet to include the policy in the configuration
269                 updateGroup(group);
270                                 
271                 return;
272         }
273         
274         /**
275          * Copy a single Policy file from the input stream to the PAP Servlet.
276          * Either this works (silently) or it throws an exception.
277          * 
278          * @param policyId
279          * @param group
280          * @param policy
281          * @return
282          * @throws PAPException
283          */
284         public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
285                 // send the policy file to the PAP Servlet
286                 try {
287                         sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
288                 } catch (Exception e) {
289                         String message = "Unable to PUT policy '" + policyId + "', e:" + e;
290                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
291                         throw new PAPException(message);
292                 }
293         }
294         
295
296         @Override
297         public void     copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
298                 if (policy == null || group == null) {
299                         throw new PAPException("Null input policy="+policy+"  group="+group);
300                 }
301                 try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
302                         copyFile(policy.getId(), group, is );
303                 } catch (Exception e) {
304                         String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
305                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
306                         throw new PAPException(message);
307                 }
308         }
309         
310         @Override
311         public void     removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
312                 throw new PAPException("NOT IMPLEMENTED");
313
314         }
315
316         
317         /**
318          * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
319          * to get detailed 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         //
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
339          *      OR it is an object that is to be 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 Exception
350          */
351         @SuppressWarnings({ "rawtypes", "unchecked" })
352         private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, 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                 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
357                 Base64.Encoder encoder = Base64.getEncoder();
358                 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
359                 Object contentObj = content;
360                 LOGGER.info("Encoding for the PAP is: " + encoding);
361                 try {
362                         String fullURL = papServletURLString;
363                         if (parameters != null && parameters.length > 0) {
364                                 StringBuilder queryString = new StringBuilder();
365                                 for (String p : parameters) {
366                                         queryString.append("&" + p);
367                                 }
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                         
383                         URL url = new URL(fullURL);
384
385                         //
386                         // Open up the connection
387                         //
388                         connection = (HttpURLConnection)url.openConnection();
389                         //
390                         // Setup our method and headers
391                         //
392             connection.setRequestMethod(method);
393             connection.setUseCaches(false);
394             //
395             // Adding this in. It seems the HttpUrlConnection class does NOT
396             // properly forward our headers for POST re-direction. It does so
397             // for a GET re-direction.
398             //
399             // So we need to handle this ourselves.
400             //
401             connection.setInstanceFollowRedirects(false);
402             connection.setRequestProperty("Authorization", "Basic " + encoding);
403                         connection.setDoOutput(true);
404                         connection.setDoInput(true);
405                         
406                         if (contentObj != null) {
407                                 if (contentObj instanceof InputStream) {
408                                 try {
409                                         //
410                                         // Send our current policy configuration
411                                         //
412                                         try (OutputStream os = connection.getOutputStream()) {
413                                                 int count = IOUtils.copy((InputStream)contentObj, os);
414                                                 if (LOGGER.isDebugEnabled()) {
415                                                         LOGGER.debug("copied to output, bytes="+count);
416                                                 }
417                                         }
418                                 } catch (Exception e) {
419                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
420                                 }
421                                 } else {
422                                         // The contentObj is an object to be encoded in JSON
423                             ObjectMapper mapper = new ObjectMapper();
424                             mapper.writeValue(connection.getOutputStream(),  contentObj);
425                                 }
426                         }
427             //
428             // Do the connect
429             //
430             connection.connect();
431             if (connection.getResponseCode() == 204) {
432                 LOGGER.info("Success - no content.");
433                 return null;
434             } else if (connection.getResponseCode() == 200) {
435                 LOGGER.info("Success. We have a return object.");
436                 String isValidData = connection.getHeaderField("isValidData");
437                 String isSuccess = connection.getHeaderField("successMapKey");
438                 Map<String, String> successMap = new HashMap<>();
439                 if (isValidData != null && "true".equalsIgnoreCase(isValidData)){
440                     LOGGER.info("Policy Data is valid.");       
441                         return true;
442                 } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) {
443                     LOGGER.info("Policy Data is invalid.");     
444                         return false;
445                 } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) {
446                         LOGGER.info("Policy Created Successfully!" );
447                         String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
448                         successMap.put("success", finalPolicyPath);
449                         return successMap;
450                 } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) {
451                         LOGGER.info("There was an error while creating the policy!");
452                         successMap.put("error", "error");
453                         return successMap;
454                 } else {
455                         // get the response content into a String
456                         String json = null;
457                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
458                             java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
459                             scanner.useDelimiter("\\A");
460                             json =  scanner.hasNext() ? scanner.next() : "";
461                             scanner.close();
462                             LOGGER.info("JSON response from PAP: " + json);
463                         
464                         // convert Object sent as JSON into local object
465                             ObjectMapper mapper = new ObjectMapper();
466                             mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
467                             if (collectionTypeClass != null) {
468                                 // collection of objects expected
469                                 final CollectionType javaType = 
470                                       mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
471         
472                                 return mapper.readValue(json, javaType);
473                             } else {
474                                 // single value object expected
475                                     return mapper.readValue(json, responseContentClass);
476                             }
477                 }
478
479             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode()  <= 399) {
480                 // redirection
481                 String newURL = connection.getHeaderField("Location");
482                 if (newURL == null) {
483                         LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode());
484                         throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
485                 }
486                 int qIndex = newURL.indexOf('?');
487                 if (qIndex > 0) {
488                         newURL = newURL.substring(0, qIndex);
489                 }
490                 LOGGER.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
491                 return newURL;
492             } else {
493                 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
494                 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
495             }
496
497                 } catch (Exception e) {
498                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
499                         throw new PAPException("Request/Response threw :" + e);
500                 } finally {
501                         // cleanup the connection
502                         if (connection != null) {
503                                 try {
504                                         // For some reason trying to get the inputStream from the connection
505                                         // throws an exception rather than returning null when the InputStream does not exist.
506                                         InputStream is = connection.getInputStream();
507                                         if (is != null) {
508                                                 is.close();
509                                         }
510                                 } catch (IOException ex) {
511                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
512                                 }
513                                 connection.disconnect();
514                         }
515                 }
516         }
517 }