2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 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.Arrays;
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.PeCryptoUtils;
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 GROUP_ID = "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
86 * @throws PAPException When failing to register with PAP
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");
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, GROUP_ID, "default=");
125 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
126 sendToPAP("POST", null, null, null, GROUP_ID + 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, GROUP_ID);
134 return Collections.unmodifiableSet(newGroupSet);
138 public OnapPDPGroup getGroup(String id) throws PAPException {
139 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
143 public void newGroup(String name, String description)
144 throws PAPException {
146 String escapedDescription;
148 escapedName = URLEncoder.encode(name, "UTF-8");
149 escapedDescription = URLEncoder.encode(description, "UTF-8");
150 } catch (UnsupportedEncodingException e) {
151 throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e);
154 this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
158 * Update the configuration on the PAP for a single Group.
162 * @throws PAPException
165 public void updateGroup(OnapPDPGroup group) throws PAPException {
168 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
170 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
172 // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
173 // This is not efficient since most of the policies will already exist there.
174 // 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.
175 // now update the group object on the PAP
176 sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
177 } catch (Exception e) {
178 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
179 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
180 throw new PAPException(message);
185 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
186 String moveToGroupString = null;
187 if (newGroup != null) {
188 moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
190 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
194 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
195 return getPDPGroup(pdp.getId());
198 public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
199 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId, "getPDPGroup=");
203 public OnapPDP getPDP(String pdpId) throws PAPException {
204 return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
208 public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException {
209 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
210 sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
214 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
215 sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
219 public void updatePDP(OnapPDP pdp) throws PAPException {
220 OnapPDPGroup group = getPDPGroup(pdp);
221 sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
225 public void removePDP(OnapPDP pdp) throws PAPException {
226 OnapPDPGroup group = getPDPGroup(pdp);
227 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
230 //Validate the Policy Data
231 public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
232 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
234 //send JSON object to PAP
235 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
241 public void publishPolicy(String id, String name, boolean isRoot,
242 InputStream policy, OnapPDPGroup group) throws PAPException {
243 // copy the (one) file into the target directory on the PAP servlet
244 copyFile(id, group, policy);
246 // adjust the local copy of the group to include the new policy
247 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
248 group.getPolicies().add(pdpPolicy);
250 // tell the PAP servlet to include the policy in the configuration
255 * Copy a single Policy file from the input stream to the PAP Servlet.
256 * Either this works (silently) or it throws an exception.
262 * @throws PAPException
264 public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
265 // send the policy file to the PAP Servlet
267 sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId="+policyId);
268 } catch (Exception e) {
269 String message = "Unable to PUT policy '" + policyId + "', e:" + e;
270 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
271 throw new PAPException(message);
276 public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
277 if (policy == null || group == null) {
278 throw new PAPException("Null input policy="+policy+" group="+group);
280 try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
281 copyFile(policy.getId(), group, is );
282 } catch (Exception e) {
283 String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
284 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
285 throw new PAPException(message);
290 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
291 throw new PAPException("NOT IMPLEMENTED");
295 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
296 * to get detailed status info.
300 * @throws PAPException
303 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
304 return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
308 // Internal Operations called by the PAPEngine Interface methods
312 * Send a request to the PAP Servlet and get the response.
314 * The content is either an InputStream to be copied to the Request OutputStream
315 * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
317 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
320 * @param content - EITHER an InputStream OR an Object to be encoded in JSON
321 * @param collectionTypeClass
322 * @param responseContentClass
325 * @throws PAPException
327 @SuppressWarnings({ "rawtypes", "unchecked" })
328 private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
329 HttpURLConnection connection = null;
330 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
331 LOGGER.info("User Id is " + papID);
332 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
333 String papPass = PeCryptoUtils
334 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
335 Base64.Encoder encoder = Base64.getEncoder();
336 String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
337 Object contentObj = content;
338 LOGGER.info("Encoding for the PAP is: " + encoding);
340 String fullURL = papServletURLString;
341 if (parameters != null && parameters.length > 0) {
342 StringBuilder queryString = new StringBuilder();
343 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
344 fullURL += "?" + queryString.substring(1);
347 // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
348 if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
349 // Adjust the url and properties appropriately
350 String pdpID = ((OnapPDP) contentObj).getId();
351 fullURL = pdpID + "?type=Status";
353 if (CheckPDP.validateID(pdpID)) {
354 encoding = CheckPDP.getEncoding(pdpID);
358 URL url = new URL(fullURL);
361 // Open up the connection
363 connection = (HttpURLConnection) url.openConnection();
365 // Setup our method and headers
367 connection.setRequestMethod(method);
368 connection.setUseCaches(false);
370 // Adding this in. It seems the HttpUrlConnection class does NOT
371 // properly forward our headers for POST re-direction. It does so
372 // for a GET re-direction.
374 // So we need to handle this ourselves.
376 connection.setInstanceFollowRedirects(false);
377 connection.setRequestProperty("Authorization", "Basic " + encoding);
378 connection.setDoOutput(true);
379 connection.setDoInput(true);
381 if (contentObj != null) {
382 if (contentObj instanceof InputStream) {
383 sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
385 // The contentObj is an object to be encoded in JSON
386 ObjectMapper mapper = new ObjectMapper();
387 mapper.writeValue(connection.getOutputStream(), contentObj);
393 connection.connect();
394 if (connection.getResponseCode() == 204) {
395 LOGGER.info("Success - no content.");
397 } else if (connection.getResponseCode() == 200) {
398 LOGGER.info("Success. We have a return object.");
399 String isValidData = connection.getHeaderField("isValidData");
400 String isSuccess = connection.getHeaderField("successMapKey");
401 Map<String, String> successMap = new HashMap<>();
402 if ("true".equalsIgnoreCase(isValidData)) {
403 LOGGER.info("Policy Data is valid.");
405 } else if ("false".equalsIgnoreCase(isValidData)) {
406 LOGGER.info("Policy Data is invalid.");
408 } else if ("success".equalsIgnoreCase(isSuccess)) {
409 LOGGER.info("Policy Created Successfully!");
410 String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
411 successMap.put("success", finalPolicyPath);
413 } else if ("error".equalsIgnoreCase(isSuccess)) {
414 LOGGER.info("There was an error while creating the policy!");
415 successMap.put("error", "error");
418 // get the response content into a String
419 String json = getJsonString(connection);
421 // convert Object sent as JSON into local object
422 ObjectMapper mapper = new ObjectMapper();
423 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
424 if (collectionTypeClass != null) {
425 // collection of objects expected
426 final CollectionType javaType =
427 mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
428 return mapper.readValue(json, javaType);
430 // single value object expected
431 return mapper.readValue(json, responseContentClass);
434 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
436 String newURL = connection.getHeaderField("Location");
437 if (newURL == null) {
439 .error("No Location header to redirect to when response code=" + connection.getResponseCode());
440 throw new IOException(
441 "No redirect Location header when response code=" + connection.getResponseCode());
443 int qIndex = newURL.indexOf('?');
445 newURL = newURL.substring(0, qIndex);
447 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
450 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection
451 .getResponseMessage());
452 throw new IOException(
453 "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
455 } catch (Exception e) {
456 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
457 throw new PAPException("Request/Response threw :" + e);
459 // cleanup the connection
460 if (connection != null) {
462 // For some reason trying to get the inputStream from the connection
463 // throws an exception rather than returning null when the InputStream does not exist.
464 InputStream is = connection.getInputStream();
468 } catch (IOException ex) {
469 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
471 connection.disconnect();
476 private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
479 // Send our current policy configuration
481 try (OutputStream os = connection.getOutputStream()) {
482 int count = IOUtils.copy(contentObj, os);
483 if (LOGGER.isDebugEnabled()) {
484 LOGGER.debug("copied to output, bytes="+count);
487 } catch (Exception e) {
488 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
492 private String getJsonString(final HttpURLConnection connection) throws IOException {
494 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
495 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
496 scanner.useDelimiter("\\A");
497 json = scanner.hasNext() ? scanner.next() : "";
498 } catch (Exception e){
499 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e, e);
502 LOGGER.info("JSON response from PAP: " + json);