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;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.UnsupportedEncodingException;
39 import java.net.HttpURLConnection;
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;
51 import org.apache.commons.io.IOUtils;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.rest.XACMLRestProperties;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.utils.PeCryptoUtils;
57 import org.onap.policy.xacml.api.XACMLErrorConstants;
58 import org.onap.policy.xacml.api.pap.OnapPDP;
59 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
60 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
61 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
62 import org.onap.policy.xacml.std.pap.StdPDP;
63 import org.onap.policy.xacml.std.pap.StdPDPGroup;
64 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
65 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
66 import org.onap.policy.xacml.std.pap.StdPDPStatus;
69 * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
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
87 * @throws PAPException When failing to register with PAP
89 public RESTfulPAPEngine(String myURLString) throws PAPException {
91 // Get our URL to the PAP servlet
93 this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
94 if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
96 "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP.";
97 LOGGER.error(message);
98 throw new PAPException(message);
102 // register this Admin Console with the PAP Servlet to get updates
104 Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
105 if (newURL != null) {
106 // assume this was a re-direct and try again
107 LOGGER.warn("Redirecting to '" + newURL + "'");
108 this.papServletURLString = (String) newURL;
109 newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
110 if (newURL != null) {
111 LOGGER.error("Failed to redirect to " + this.papServletURLString);
112 throw new PAPException("Failed to register with PAP");
118 // High-level commands used by the Admin Console code through the PAPEngine Interface
122 public OnapPDPGroup getDefaultGroup() throws PAPException {
123 return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
127 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
128 sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
131 @SuppressWarnings("unchecked")
133 public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
134 Set<OnapPDPGroup> newGroupSet;
135 newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
136 return Collections.unmodifiableSet(newGroupSet);
140 public OnapPDPGroup getGroup(String id) throws PAPException {
141 return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
145 public void newGroup(String name, String description) throws PAPException {
147 String escapedDescription;
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, GROUP_ID, "groupName=" + escapedName,
156 "groupDescription=" + escapedDescription);
160 * Update the configuration on the PAP for a single Group.
164 * @throws PAPException
167 public void updateGroup(OnapPDPGroup group) throws PAPException {
170 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on
173 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the
176 // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
177 // This is not efficient since most of the policies will already exist there.
178 // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any
179 // corrupted files on the PAP get refreshed.
180 // now update the group object on the PAP
181 sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
182 } catch (Exception e) {
183 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
184 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
185 throw new PAPException(message);
190 * Passing UserName to PAP Rest for Audit Logging.
192 * @see org.onap.policy.xacml.api.pap.PAPPolicyEngine#updateGroup(org.onap.policy.xacml.api.pap.OnapPDPGroup,
196 public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
198 sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
199 } catch (Exception e) {
200 String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
201 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
202 throw new PAPException(message);
207 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
208 String moveToGroupString = null;
209 if (newGroup != null) {
210 moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
212 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
216 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
217 return getPDPGroup(pdp.getId());
220 public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
221 return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
226 public OnapPDP getPDP(String pdpId) throws PAPException {
227 return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
231 public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
232 throws PAPException {
233 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
234 sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
238 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
239 sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
243 public void updatePDP(OnapPDP pdp) throws PAPException {
244 OnapPDPGroup group = getPDPGroup(pdp);
245 sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
249 public void removePDP(OnapPDP pdp) throws PAPException {
250 OnapPDPGroup group = getPDPGroup(pdp);
251 sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
254 // Validate the Policy Data
255 public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
256 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
257 policyAdapter.getConfigType(), "Base");
259 // send JSON object to PAP
260 return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
261 "policyType=" + policyType);
265 public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group)
266 throws PAPException {
267 // copy the (one) file into the target directory on the PAP servlet
268 copyFile(id, group, policy);
270 // adjust the local copy of the group to include the new policy
271 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
272 group.getPolicies().add(pdpPolicy);
274 // tell the PAP servlet to include the policy in the configuration
279 * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
286 * @throws PAPException
288 public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
289 // send the policy file to the PAP Servlet
291 sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
292 } catch (Exception e) {
293 String message = "Unable to PUT policy '" + policyId + "', e:" + e;
294 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
295 throw new PAPException(message);
300 public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
301 if (policy == null || group == null) {
302 throw new PAPException("Null input policy=" + policy + " group=" + group);
304 try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
305 copyFile(policy.getId(), group, is);
306 } catch (Exception e) {
307 String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
308 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
309 throw new PAPException(message);
314 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
315 throw new PAPException("NOT IMPLEMENTED");
319 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
324 * @throws PAPException
327 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
328 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 OR it is an object that is to be
339 * 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
349 * @throws PAPException
351 @SuppressWarnings({"rawtypes", "unchecked"})
352 private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
353 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 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
358 String papPass = PeCryptoUtils
359 .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
360 Base64.Encoder encoder = Base64.getEncoder();
361 String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
362 Object contentObj = content;
363 LOGGER.info("Encoding for the PAP is: " + encoding);
365 String fullURL = papServletURLString;
366 if (parameters != null && parameters.length > 0) {
367 StringBuilder queryString = new StringBuilder();
368 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
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 // Open up the connection
386 connection = (HttpURLConnection) makeConnection(fullURL);
388 // Setup our method and headers
390 connection.setRequestMethod(method);
391 connection.setUseCaches(false);
393 // Adding this in. It seems the HttpUrlConnection class does NOT
394 // properly forward our headers for POST re-direction. It does so
395 // for a GET re-direction.
397 // So we need to handle this ourselves.
399 connection.setInstanceFollowRedirects(false);
400 connection.setRequestProperty("Authorization", "Basic " + encoding);
401 connection.setDoOutput(true);
402 connection.setDoInput(true);
404 if (contentObj != null) {
405 if (contentObj instanceof InputStream) {
406 sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
408 // The contentObj is an object to be encoded in JSON
409 ObjectMapper mapper = new ObjectMapper();
410 mapper.writeValue(connection.getOutputStream(), contentObj);
416 connection.connect();
417 if (connection.getResponseCode() == 204) {
418 LOGGER.info("Success - no content.");
420 } else if (connection.getResponseCode() == 200) {
421 LOGGER.info("Success. We have a return object.");
422 String isValidData = connection.getHeaderField("isValidData");
423 String isSuccess = connection.getHeaderField("successMapKey");
424 Map<String, String> successMap = new HashMap<>();
425 if ("true".equalsIgnoreCase(isValidData)) {
426 LOGGER.info("Policy Data is valid.");
428 } else if ("false".equalsIgnoreCase(isValidData)) {
429 LOGGER.info("Policy Data is invalid.");
431 } else if ("success".equalsIgnoreCase(isSuccess)) {
432 LOGGER.info("Policy Created Successfully!");
433 String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
434 successMap.put("success", finalPolicyPath);
436 } else if ("error".equalsIgnoreCase(isSuccess)) {
437 LOGGER.info("There was an error while creating the policy!");
438 successMap.put("error", "error");
441 // get the response content into a String
442 String json = getJsonString(connection);
444 // convert Object sent as JSON into local object
445 ObjectMapper mapper = new ObjectMapper();
446 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
447 if (collectionTypeClass != null) {
448 // collection of objects expected
449 final CollectionType javaType = mapper.getTypeFactory()
450 .constructCollectionType(collectionTypeClass, responseContentClass);
451 return mapper.readValue(json, javaType);
453 // single value object expected
454 return mapper.readValue(json, responseContentClass);
457 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
459 String newURL = connection.getHeaderField("Location");
460 if (newURL == null) {
462 "No Location header to redirect to when response code=" + connection.getResponseCode());
463 throw new IOException(
464 "No redirect Location header when response code=" + connection.getResponseCode());
466 int qIndex = newURL.indexOf('?');
468 newURL = newURL.substring(0, qIndex);
470 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
473 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: "
474 + connection.getResponseMessage());
475 throw new IOException(
476 "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
478 } catch (Exception e) {
479 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
480 throw new PAPException("Request/Response threw :" + e);
482 // cleanup the connection
483 if (connection != null) {
485 // For some reason trying to get the inputStream from the connection
486 // throws an exception rather than returning null when the InputStream does not exist.
487 InputStream is = connection.getInputStream();
491 } catch (IOException ex) {
492 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
494 connection.disconnect();
499 private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
502 // Send our current policy configuration
504 try (OutputStream os = connection.getOutputStream()) {
505 int count = IOUtils.copy(contentObj, os);
506 if (LOGGER.isDebugEnabled()) {
507 LOGGER.debug("copied to output, bytes=" + count);
510 } catch (Exception e) {
511 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
515 private String getJsonString(final HttpURLConnection connection) throws IOException {
517 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
518 try (java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
519 scanner.useDelimiter("\\A");
520 json = scanner.hasNext() ? scanner.next() : "";
521 } catch (Exception e) {
522 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e,
526 LOGGER.info("JSON response from PAP: " + json);
530 // these may be overridden by junit tests
532 protected URLConnection makeConnection(String fullURL) throws IOException {
533 return new URL(fullURL).openConnection();