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 * 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.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 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 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
333 Base64.Encoder encoder = Base64.getEncoder();
334 String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
335 Object contentObj = content;
336 LOGGER.info("Encoding for the PAP is: " + encoding);
338 String fullURL = papServletURLString;
339 if (parameters != null && parameters.length > 0) {
340 StringBuilder queryString = new StringBuilder();
341 Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
342 fullURL += "?" + queryString.substring(1);
345 // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
346 if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
347 // Adjust the url and properties appropriately
348 String pdpID = ((OnapPDP) contentObj).getId();
349 fullURL = pdpID + "?type=Status";
351 if (CheckPDP.validateID(pdpID)) {
352 encoding = CheckPDP.getEncoding(pdpID);
356 URL url = new URL(fullURL);
359 // Open up the connection
361 connection = (HttpURLConnection) url.openConnection();
363 // Setup our method and headers
365 connection.setRequestMethod(method);
366 connection.setUseCaches(false);
368 // Adding this in. It seems the HttpUrlConnection class does NOT
369 // properly forward our headers for POST re-direction. It does so
370 // for a GET re-direction.
372 // So we need to handle this ourselves.
374 connection.setInstanceFollowRedirects(false);
375 connection.setRequestProperty("Authorization", "Basic " + encoding);
376 connection.setDoOutput(true);
377 connection.setDoInput(true);
379 if (contentObj != null) {
380 if (contentObj instanceof InputStream) {
381 sendCurrPolicyConfig(method, connection, (InputStream) contentObj);
383 // The contentObj is an object to be encoded in JSON
384 ObjectMapper mapper = new ObjectMapper();
385 mapper.writeValue(connection.getOutputStream(), contentObj);
391 connection.connect();
392 if (connection.getResponseCode() == 204) {
393 LOGGER.info("Success - no content.");
395 } else if (connection.getResponseCode() == 200) {
396 LOGGER.info("Success. We have a return object.");
397 String isValidData = connection.getHeaderField("isValidData");
398 String isSuccess = connection.getHeaderField("successMapKey");
399 Map<String, String> successMap = new HashMap<>();
400 if ("true".equalsIgnoreCase(isValidData)) {
401 LOGGER.info("Policy Data is valid.");
403 } else if ("false".equalsIgnoreCase(isValidData)) {
404 LOGGER.info("Policy Data is invalid.");
406 } else if ("success".equalsIgnoreCase(isSuccess)) {
407 LOGGER.info("Policy Created Successfully!");
408 String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
409 successMap.put("success", finalPolicyPath);
411 } else if ("error".equalsIgnoreCase(isSuccess)) {
412 LOGGER.info("There was an error while creating the policy!");
413 successMap.put("error", "error");
416 // get the response content into a String
417 String json = getJsonString(connection);
419 // convert Object sent as JSON into local object
420 ObjectMapper mapper = new ObjectMapper();
421 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
422 if (collectionTypeClass != null) {
423 // collection of objects expected
424 final CollectionType javaType =
425 mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
426 return mapper.readValue(json, javaType);
428 // single value object expected
429 return mapper.readValue(json, responseContentClass);
432 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
434 String newURL = connection.getHeaderField("Location");
435 if (newURL == null) {
437 .error("No Location header to redirect to when response code=" + connection.getResponseCode());
438 throw new IOException(
439 "No redirect Location header when response code=" + connection.getResponseCode());
441 int qIndex = newURL.indexOf('?');
443 newURL = newURL.substring(0, qIndex);
445 LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
448 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection
449 .getResponseMessage());
450 throw new IOException(
451 "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
453 } catch (Exception e) {
454 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
455 throw new PAPException("Request/Response threw :" + e);
457 // cleanup the connection
458 if (connection != null) {
460 // For some reason trying to get the inputStream from the connection
461 // throws an exception rather than returning null when the InputStream does not exist.
462 InputStream is = connection.getInputStream();
466 } catch (IOException ex) {
467 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
469 connection.disconnect();
474 private void sendCurrPolicyConfig(String method, final HttpURLConnection connection, InputStream contentObj) {
477 // Send our current policy configuration
479 try (OutputStream os = connection.getOutputStream()) {
480 int count = IOUtils.copy(contentObj, os);
481 if (LOGGER.isDebugEnabled()) {
482 LOGGER.debug("copied to output, bytes="+count);
485 } catch (Exception e) {
486 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
490 private String getJsonString(final HttpURLConnection connection) throws IOException {
492 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
493 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
494 scanner.useDelimiter("\\A");
495 json = scanner.hasNext() ? scanner.next() : "";
496 } catch (Exception e){
497 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to read inputStream from connection: " + e, e);
500 LOGGER.info("JSON response from PAP: " + json);