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;
25 import com.att.research.xacml.api.pap.PAPException;
26 import com.att.research.xacml.api.pap.PDPPolicy;
27 import com.att.research.xacml.api.pap.PDPStatus;
28 import com.att.research.xacml.util.XACMLProperties;
29 import com.fasterxml.jackson.databind.DeserializationFeature;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.type.CollectionType;
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.UnsupportedEncodingException;
38 import java.net.HttpURLConnection;
39 import java.net.MalformedURLException;
41 import java.net.URLConnection;
42 import java.net.URLEncoder;
43 import java.nio.charset.StandardCharsets;
44 import java.util.Arrays;
45 import java.util.Base64;
46 import java.util.Collections;
47 import java.util.HashMap;
50 import org.apache.commons.io.IOUtils;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.rest.XACMLRestProperties;
54 import org.onap.policy.rest.adapter.PolicyRestAdapter;
55 import org.onap.policy.utils.PeCryptoUtils;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.OnapPDP;
58 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
59 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
60 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
61 import org.onap.policy.xacml.std.pap.StdPDP;
62 import org.onap.policy.xacml.std.pap.StdPDPGroup;
63 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
64 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
65 import org.onap.policy.xacml.std.pap.StdPDPStatus;
68 * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
73 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
74 private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
76 private static final String GROUP_ID = "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
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) {
95 "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP.";
96 LOGGER.error(message);
97 throw new PAPException(message);
101 // register this Admin Console with the PAP Servlet to get updates
103 Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
104 if (newURL != null) {
105 // assume this was a re-direct and try again
106 LOGGER.warn("Redirecting to '" + newURL + "'");
107 this.papServletURLString = (String) newURL;
108 newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
109 if (newURL != null) {
110 LOGGER.error("Failed to redirect to " + this.papServletURLString);
111 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, GROUP_ID, "default=");
126 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
127 sendToPAP("POST", null, null, null, GROUP_ID + 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, GROUP_ID);
135 return Collections.unmodifiableSet(newGroupSet);
139 public OnapPDPGroup getGroup(String id) throws PAPException {
140 return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
144 public void newGroup(String name, String description) 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,
155 "groupDescription=" + escapedDescription);
159 * Update the configuration on the PAP for a single Group.
163 * @throws PAPException
166 public void updateGroup(OnapPDPGroup group) throws PAPException {
169 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on
172 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the
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
178 // corrupted files on the PAP get refreshed.
179 // now update the group object on the PAP
180 sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
181 } catch (Exception e) {
182 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
183 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
184 throw new PAPException(message);
189 * Passing UserName to PAP Rest for Audit Logging.
191 * @see org.onap.policy.xacml.api.pap.PAPPolicyEngine#updateGroup(org.onap.policy.xacml.api.pap.OnapPDPGroup,
195 public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
197 sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
198 } catch (Exception e) {
199 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
200 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
201 throw new PAPException(message);
206 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
207 String moveToGroupString = null;
208 if (newGroup != null) {
209 moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
211 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
215 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
216 return getPDPGroup(pdp.getId());
219 public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
220 return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
225 public OnapPDP getPDP(String pdpId) throws PAPException {
226 return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
230 public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
231 throws PAPException {
232 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
233 sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
237 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
238 sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
242 public void updatePDP(OnapPDP pdp) throws PAPException {
243 OnapPDPGroup group = getPDPGroup(pdp);
244 sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
248 public void removePDP(OnapPDP pdp) throws PAPException {
249 OnapPDPGroup group = getPDPGroup(pdp);
250 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
253 // Validate the Policy Data
254 public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
255 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
256 policyAdapter.getConfigType(), "Base");
258 // send JSON object to PAP
259 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
260 "policyType=" + policyType);
266 public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group)
267 throws PAPException {
268 // copy the (one) file into the target directory on the PAP servlet
269 copyFile(id, group, policy);
271 // adjust the local copy of the group to include the new policy
272 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
273 group.getPolicies().add(pdpPolicy);
275 // tell the PAP servlet to include the policy in the configuration
280 * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
287 * @throws PAPException
289 public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
290 // send the policy file to the PAP Servlet
292 sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
293 } catch (Exception e) {
294 String message = "Unable to PUT policy '" + policyId + "', e:" + e;
295 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
296 throw new PAPException(message);
301 public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
302 if (policy == null || group == null) {
303 throw new PAPException("Null input policy=" + policy + " group=" + group);
305 try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
306 copyFile(policy.getId(), group, is);
307 } catch (Exception e) {
308 String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
309 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
310 throw new PAPException(message);
315 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
316 throw new PAPException("NOT IMPLEMENTED");
320 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
325 * @throws PAPException
328 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
329 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 OR it is an object that is to be
340 * 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
350 * @throws PAPException
352 @SuppressWarnings({"rawtypes", "unchecked"})
353 private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
354 String... parameters) throws PAPException {
355 HttpURLConnection connection = null;
356 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
357 LOGGER.info("User Id is " + papID);
358 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
359 String papPass = PeCryptoUtils
360 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
361 Base64.Encoder encoder = Base64.getEncoder();
362 String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
363 Object contentObj = content;
364 LOGGER.info("Encoding for the PAP is: " + encoding);
366 String fullURL = papServletURLString;
367 if (parameters != null && parameters.length > 0) {
368 StringBuilder queryString = new StringBuilder();
369 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
370 fullURL += "?" + queryString.substring(1);
373 // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
374 if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
375 // Adjust the url and properties appropriately
376 String pdpID = ((OnapPDP) contentObj).getId();
377 fullURL = pdpID + "?type=Status";
379 if (CheckPDP.validateID(pdpID)) {
380 encoding = CheckPDP.getEncoding(pdpID);
385 // Open up the connection
387 connection = (HttpURLConnection) makeConnection(fullURL);
389 // Setup our method and headers
391 connection.setRequestMethod(method);
392 connection.setUseCaches(false);
394 // Adding this in. It seems the HttpUrlConnection class does NOT
395 // properly forward our headers for POST re-direction. It does so
396 // for a GET re-direction.
398 // So we need to handle this ourselves.
400 connection.setInstanceFollowRedirects(false);
401 connection.setRequestProperty("Authorization", "Basic " + encoding);
402 connection.setDoOutput(true);
403 connection.setDoInput(true);
405 if (contentObj != null) {
406 if (contentObj instanceof InputStream) {
407 sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
409 // The contentObj is an object to be encoded in JSON
410 ObjectMapper mapper = new ObjectMapper();
411 mapper.writeValue(connection.getOutputStream(), contentObj);
417 connection.connect();
418 if (connection.getResponseCode() == 204) {
419 LOGGER.info("Success - no content.");
421 } else if (connection.getResponseCode() == 200) {
422 LOGGER.info("Success. We have a return object.");
423 String isValidData = connection.getHeaderField("isValidData");
424 String isSuccess = connection.getHeaderField("successMapKey");
425 Map<String, String> successMap = new HashMap<>();
426 if ("true".equalsIgnoreCase(isValidData)) {
427 LOGGER.info("Policy Data is valid.");
429 } else if ("false".equalsIgnoreCase(isValidData)) {
430 LOGGER.info("Policy Data is invalid.");
432 } else if ("success".equalsIgnoreCase(isSuccess)) {
433 LOGGER.info("Policy Created Successfully!");
434 String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
435 successMap.put("success", finalPolicyPath);
437 } else if ("error".equalsIgnoreCase(isSuccess)) {
438 LOGGER.info("There was an error while creating the policy!");
439 successMap.put("error", "error");
442 // get the response content into a String
443 String json = getJsonString(connection);
445 // convert Object sent as JSON into local object
446 ObjectMapper mapper = new ObjectMapper();
447 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
448 if (collectionTypeClass != null) {
449 // collection of objects expected
450 final CollectionType javaType = mapper.getTypeFactory()
451 .constructCollectionType(collectionTypeClass, responseContentClass);
452 return mapper.readValue(json, javaType);
454 // single value object expected
455 return mapper.readValue(json, responseContentClass);
458 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
460 String newURL = connection.getHeaderField("Location");
461 if (newURL == null) {
463 "No Location header to redirect to when response code=" + connection.getResponseCode());
464 throw new IOException(
465 "No redirect Location header when response code=" + connection.getResponseCode());
467 int qIndex = newURL.indexOf('?');
469 newURL = newURL.substring(0, qIndex);
471 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
474 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: "
475 + connection.getResponseMessage());
476 throw new IOException(
477 "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
479 } catch (Exception e) {
480 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
481 throw new PAPException("Request/Response threw :" + e);
483 // cleanup the connection
484 if (connection != null) {
486 // For some reason trying to get the inputStream from the connection
487 // throws an exception rather than returning null when the InputStream does not exist.
488 InputStream is = connection.getInputStream();
492 } catch (IOException ex) {
493 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
495 connection.disconnect();
500 private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
503 // Send our current policy configuration
505 try (OutputStream os = connection.getOutputStream()) {
506 int count = IOUtils.copy(contentObj, os);
507 if (LOGGER.isDebugEnabled()) {
508 LOGGER.debug("copied to output, bytes=" + count);
511 } catch (Exception e) {
512 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
516 private String getJsonString(final HttpURLConnection connection) throws IOException {
518 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
519 try (java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
520 scanner.useDelimiter("\\A");
521 json = scanner.hasNext() ? scanner.next() : "";
522 } catch (Exception e) {
523 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e,
527 LOGGER.info("JSON response from PAP: " + json);
531 // these may be overridden by junit tests
533 protected URLConnection makeConnection(String fullURL) throws IOException {
534 return new URL(fullURL).openConnection();