2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.admin;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.io.UnsupportedEncodingException;
32 import java.net.HttpURLConnection;
34 import java.net.URLEncoder;
35 import java.nio.charset.StandardCharsets;
36 import java.util.Base64;
37 import java.util.Collections;
38 import java.util.HashMap;
42 import org.apache.commons.io.IOUtils;
43 import org.onap.policy.rest.XACMLRestProperties;
44 import org.onap.policy.rest.adapter.PolicyRestAdapter;
45 import org.onap.policy.utils.CryptoUtils;
46 import org.onap.policy.xacml.api.XACMLErrorConstants;
47 import org.onap.policy.xacml.api.pap.OnapPDP;
48 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
49 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
50 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
51 import org.onap.policy.xacml.std.pap.StdPDP;
52 import org.onap.policy.xacml.std.pap.StdPDPGroup;
53 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
54 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
55 import org.onap.policy.xacml.std.pap.StdPDPStatus;
57 import com.att.research.xacml.api.pap.PAPException;
58 import com.att.research.xacml.api.pap.PDPPolicy;
59 import com.att.research.xacml.api.pap.PDPStatus;
60 import com.att.research.xacml.util.XACMLProperties;
61 import com.fasterxml.jackson.databind.DeserializationFeature;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import com.fasterxml.jackson.databind.type.CollectionType;
65 import org.onap.policy.common.logging.flexlogger.FlexLogger;
66 import org.onap.policy.common.logging.flexlogger.Logger;
69 * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
70 * through a RESTful interface
74 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
75 private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
77 private static final String groupID = "groupId=";
80 // URL of the PAP Servlet that this Admin Console talks to
82 private String papServletURLString;
85 * Set up link with PAP Servlet and get our initial set of Groups
88 public RESTfulPAPEngine (String myURLString) throws PAPException {
90 // Get our URL to the PAP servlet
92 this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
93 if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
94 String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP.";
95 LOGGER.error(message);
96 throw new PAPException(message);
100 // register this Admin Console with the PAP Servlet to get updates
102 Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
103 if (newURL != null) {
104 // assume this was a re-direct and try again
105 LOGGER.warn("Redirecting to '" + newURL + "'");
106 this.papServletURLString = (String)newURL;
107 newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
108 if (newURL != null) {
109 LOGGER.error("Failed to redirect to " + this.papServletURLString);
110 throw new PAPException("Failed to register with PAP");
117 // High-level commands used by the Admin Console code through the PAPEngine Interface
121 public OnapPDPGroup getDefaultGroup() throws PAPException {
122 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default=");
126 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
127 sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true");
130 @SuppressWarnings("unchecked")
132 public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
133 Set<OnapPDPGroup> newGroupSet;
134 newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID);
135 return Collections.unmodifiableSet(newGroupSet);
140 public OnapPDPGroup getGroup(String id) throws PAPException {
141 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
145 public void newGroup(String name, String description)
146 throws PAPException {
147 String escapedName = null;
148 String escapedDescription = null;
150 escapedName = URLEncoder.encode(name, "UTF-8");
151 escapedDescription = URLEncoder.encode(description, "UTF-8");
152 } catch (UnsupportedEncodingException e) {
153 throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e);
156 this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
161 * Update the configuration on the PAP for a single Group.
165 * @throws PAPException
168 public void updateGroup(OnapPDPGroup group) throws PAPException {
173 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
175 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
179 // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
180 // This is not efficient since most of the policies will already exist there.
181 // 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.
184 // now update the group object on the PAP
186 sendToPAP("PUT", group, null, null, groupID + group.getId());
187 } catch (Exception e) {
188 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
189 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
190 throw new PAPException(message);
196 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
197 throws PAPException {
198 String moveToGroupString = null;
199 if (newGroup != null) {
200 moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
202 sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
206 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
207 return getPDPGroup(pdp.getId());
211 public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
212 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
216 public OnapPDP getPDP(String pdpId) throws PAPException {
217 return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
221 public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException {
222 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
223 sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
228 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
229 sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
234 public void updatePDP(OnapPDP pdp) throws PAPException {
235 OnapPDPGroup group = getPDPGroup(pdp);
236 sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
241 public void removePDP(OnapPDP pdp) throws PAPException {
242 OnapPDPGroup group = getPDPGroup(pdp);
243 sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
247 //Validate the Policy Data
248 public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
249 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
251 //send JSON object to PAP
252 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
258 public void publishPolicy(String id, String name, boolean isRoot,
259 InputStream policy, OnapPDPGroup group) throws PAPException {
262 // copy the (one) file into the target directory on the PAP servlet
263 copyFile(id, group, policy);
265 // adjust the local copy of the group to include the new policy
266 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
267 group.getPolicies().add(pdpPolicy);
269 // tell the PAP servlet to include the policy in the configuration
276 * Copy a single Policy file from the input stream to the PAP Servlet.
277 * Either this works (silently) or it throws an exception.
283 * @throws PAPException
285 public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
286 // send the policy file to the PAP Servlet
288 sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
289 } catch (Exception e) {
290 String message = "Unable to PUT policy '" + policyId + "', e:" + e;
291 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
292 throw new PAPException(message);
298 public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
299 if (policy == null || group == null) {
300 throw new PAPException("Null input policy="+policy+" group="+group);
302 try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
303 copyFile(policy.getId(), group, is );
304 } catch (Exception e) {
305 String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
306 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
307 throw new PAPException(message);
312 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
313 throw new PAPException("NOT IMPLEMENTED");
319 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
320 * to get detailed status info.
324 * @throws PAPException
327 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
328 return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
333 // Internal Operations called by the PAPEngine Interface methods
337 * Send a request to the PAP Servlet and get the response.
339 * The content is either an InputStream to be copied to the Request OutputStream
340 * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
342 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
345 * @param content - EITHER an InputStream OR an Object to be encoded in JSON
346 * @param collectionTypeClass
347 * @param responseContentClass
352 @SuppressWarnings({ "rawtypes", "unchecked" })
353 private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
354 HttpURLConnection connection = null;
355 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
356 LOGGER.info("User Id is " + papID);
357 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
358 Base64.Encoder encoder = Base64.getEncoder();
359 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
360 Object contentObj = content;
361 LOGGER.info("Encoding for the PAP is: " + encoding);
363 String fullURL = papServletURLString;
364 if (parameters != null && parameters.length > 0) {
365 StringBuilder queryString = new StringBuilder();
366 for (String p : parameters) {
367 queryString.append("&" + p);
369 fullURL += "?" + queryString.substring(1);
372 // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
373 if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
374 // Adjust the url and properties appropriately
375 String pdpID =((OnapPDP)contentObj).getId();
376 fullURL = pdpID + "?type=Status";
378 if(CheckPDP.validateID(pdpID)){
379 encoding = CheckPDP.getEncoding(pdpID);
384 URL url = new URL(fullURL);
387 // Open up the connection
389 connection = (HttpURLConnection)url.openConnection();
391 // Setup our method and headers
393 connection.setRequestMethod(method);
394 connection.setUseCaches(false);
396 // Adding this in. It seems the HttpUrlConnection class does NOT
397 // properly forward our headers for POST re-direction. It does so
398 // for a GET re-direction.
400 // So we need to handle this ourselves.
402 connection.setInstanceFollowRedirects(false);
403 connection.setRequestProperty("Authorization", "Basic " + encoding);
404 connection.setDoOutput(true);
405 connection.setDoInput(true);
407 if (contentObj != null) {
408 if (contentObj instanceof InputStream) {
409 sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
411 // The contentObj is an object to be encoded in JSON
412 ObjectMapper mapper = new ObjectMapper();
413 mapper.writeValue(connection.getOutputStream(), contentObj);
419 connection.connect();
420 if (connection.getResponseCode() == 204) {
421 LOGGER.info("Success - no content.");
423 } else if (connection.getResponseCode() == 200) {
424 LOGGER.info("Success. We have a return object.");
425 String isValidData = connection.getHeaderField("isValidData");
426 String isSuccess = connection.getHeaderField("successMapKey");
427 Map<String, String> successMap = new HashMap<>();
428 if (isValidData != null && "true".equalsIgnoreCase(isValidData)){
429 LOGGER.info("Policy Data is valid.");
431 } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) {
432 LOGGER.info("Policy Data is invalid.");
434 } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) {
435 LOGGER.info("Policy Created Successfully!" );
436 String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
437 successMap.put("success", finalPolicyPath);
439 } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) {
440 LOGGER.info("There was an error while creating the policy!");
441 successMap.put("error", "error");
444 // get the response content into a String
445 String json = getJsonString(connection);
447 // convert Object sent as JSON into local object
448 ObjectMapper mapper = new ObjectMapper();
449 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
450 if (collectionTypeClass != null) {
451 // collection of objects expected
452 final CollectionType javaType =
453 mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
455 return mapper.readValue(json, javaType);
457 // single value object expected
458 return mapper.readValue(json, responseContentClass);
462 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
464 String newURL = connection.getHeaderField("Location");
465 if (newURL == null) {
466 LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode());
467 throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
469 int qIndex = newURL.indexOf('?');
471 newURL = newURL.substring(0, qIndex);
473 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
476 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
477 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
480 } catch (Exception e) {
481 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
482 throw new PAPException("Request/Response threw :" + e);
484 // cleanup the connection
485 if (connection != null) {
487 // For some reason trying to get the inputStream from the connection
488 // throws an exception rather than returning null when the InputStream does not exist.
489 InputStream is = connection.getInputStream();
493 } catch (IOException ex) {
494 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
496 connection.disconnect();
501 private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
504 // Send our current policy configuration
506 try (OutputStream os = connection.getOutputStream()) {
507 int count = IOUtils.copy(contentObj, os);
508 if (LOGGER.isDebugEnabled()) {
509 LOGGER.debug("copied to output, bytes="+count);
512 } catch (Exception e) {
513 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
517 private String getJsonString(final HttpURLConnection connection) throws IOException {
519 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
520 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
521 scanner.useDelimiter("\\A");
522 json = scanner.hasNext() ? scanner.next() : "";
523 } catch (Exception e){
524 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e, e);
527 LOGGER.info("JSON response from PAP: " + json);