2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.admin;
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;
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;
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;
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;
64 import org.onap.policy.common.logging.flexlogger.FlexLogger;
65 import org.onap.policy.common.logging.flexlogger.Logger;
68 * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
69 * through a RESTful interface
73 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
74 private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
76 private static final String groupID = "groupId=";
79 // URL of the PAP Servlet that this Admin Console talks to
81 private String papServletURLString;
84 * Set up link with PAP Servlet and get our initial set of Groups
87 public RESTfulPAPEngine (String myURLString) throws PAPException {
89 // Get our URL to the PAP servlet
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);
99 // register this Admin Console with the PAP Servlet to get updates
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");
116 // High-level commands used by the Admin Console code through the PAPEngine Interface
120 public OnapPDPGroup getDefaultGroup() throws PAPException {
121 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default=");
125 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
126 sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true");
129 @SuppressWarnings("unchecked")
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);
139 public OnapPDPGroup getGroup(String id) throws PAPException {
140 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
144 public void newGroup(String name, String description)
145 throws PAPException {
146 String escapedName = null;
147 String escapedDescription = null;
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);
155 this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
160 * Update the configuration on the PAP for a single Group.
164 * @throws PAPException
167 public void updateGroup(OnapPDPGroup group) throws PAPException {
172 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
174 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
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.
183 // now update the group object on the PAP
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);
195 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
196 throws PAPException {
197 String moveToGroupString = null;
198 if (newGroup != null) {
199 moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
201 sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
205 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
206 return getPDPGroup(pdp.getId());
210 public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
211 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
215 public OnapPDP getPDP(String pdpId) throws PAPException {
216 return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
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);
227 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
228 sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
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());
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());
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");
250 //send JSON object to PAP
251 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
257 public void publishPolicy(String id, String name, boolean isRoot,
258 InputStream policy, OnapPDPGroup group) throws PAPException {
261 // copy the (one) file into the target directory on the PAP servlet
262 copyFile(id, group, policy);
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);
268 // tell the PAP servlet to include the policy in the configuration
275 * Copy a single Policy file from the input stream to the PAP Servlet.
276 * Either this works (silently) or it throws an exception.
282 * @throws PAPException
284 public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
285 // send the policy file to the PAP Servlet
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);
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);
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);
311 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
312 throw new PAPException("NOT IMPLEMENTED");
318 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
319 * to get detailed status info.
323 * @throws PAPException
326 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
327 return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
332 // Internal Operations called by the PAPEngine Interface methods
336 * Send a request to the PAP Servlet and get the response.
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.
341 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
344 * @param content - EITHER an InputStream OR an Object to be encoded in JSON
345 * @param collectionTypeClass
346 * @param responseContentClass
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);
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);
368 fullURL += "?" + queryString.substring(1);
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";
377 if(CheckPDP.validateID(pdpID)){
378 encoding = CheckPDP.getEncoding(pdpID);
383 URL url = new URL(fullURL);
386 // Open up the connection
388 connection = (HttpURLConnection)url.openConnection();
390 // Setup our method and headers
392 connection.setRequestMethod(method);
393 connection.setUseCaches(false);
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.
399 // So we need to handle this ourselves.
401 connection.setInstanceFollowRedirects(false);
402 connection.setRequestProperty("Authorization", "Basic " + encoding);
403 connection.setDoOutput(true);
404 connection.setDoInput(true);
406 if (contentObj != null) {
407 if (contentObj instanceof InputStream) {
410 // Send our current policy configuration
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);
418 } catch (Exception e) {
419 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
422 // The contentObj is an object to be encoded in JSON
423 ObjectMapper mapper = new ObjectMapper();
424 mapper.writeValue(connection.getOutputStream(), contentObj);
430 connection.connect();
431 if (connection.getResponseCode() == 204) {
432 LOGGER.info("Success - no content.");
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.");
442 } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) {
443 LOGGER.info("Policy Data is invalid.");
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);
450 } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) {
451 LOGGER.info("There was an error while creating the policy!");
452 successMap.put("error", "error");
455 // get the response content into a String
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() : "";
462 LOGGER.info("JSON response from PAP: " + json);
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);
472 return mapper.readValue(json, javaType);
474 // single value object expected
475 return mapper.readValue(json, responseContentClass);
479 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
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());
486 int qIndex = newURL.indexOf('?');
488 newURL = newURL.substring(0, qIndex);
490 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
493 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
494 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
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);
501 // cleanup the connection
502 if (connection != null) {
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();
510 } catch (IOException ex) {
511 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
513 connection.disconnect();