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