2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.policy.pdp.rest;
23 import java.io.BufferedReader;
24 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.lang.reflect.Constructor;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.util.Properties;
34 import java.util.UUID;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.LinkedBlockingQueue;
38 import javax.servlet.Servlet;
39 import javax.servlet.ServletConfig;
40 import javax.servlet.ServletException;
41 import javax.servlet.annotation.WebInitParam;
42 import javax.servlet.annotation.WebServlet;
43 import javax.servlet.http.HttpServlet;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
47 import org.apache.commons.io.IOUtils;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.http.entity.ContentType;
51 import org.openecomp.policy.api.PolicyParameters;
52 import org.openecomp.policy.common.im.AdministrativeStateException;
53 import org.openecomp.policy.common.im.ForwardProgressException;
54 import org.openecomp.policy.common.im.IntegrityMonitor;
55 import org.openecomp.policy.common.im.IntegrityMonitorProperties;
56 import org.openecomp.policy.common.im.StandbyStatusException;
57 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
58 import org.openecomp.policy.common.logging.ECOMPLoggingUtils;
59 import org.openecomp.policy.common.logging.eelf.MessageCodes;
60 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
61 import org.openecomp.policy.pdp.rest.jmx.PdpRestMonitor;
62 import org.openecomp.policy.rest.XACMLRest;
63 import org.openecomp.policy.rest.XACMLRestProperties;
64 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
65 import org.openecomp.policy.xacml.pdp.std.functions.PolicyList;
66 import org.openecomp.policy.xacml.std.pap.StdPDPStatus;
68 import com.att.research.xacml.api.Request;
69 import com.att.research.xacml.api.Response;
70 import com.att.research.xacml.api.pap.PDPStatus.Status;
71 import com.att.research.xacml.api.pdp.PDPEngine;
72 import com.att.research.xacml.api.pdp.PDPException;
73 import com.att.research.xacml.std.dom.DOMRequest;
74 import com.att.research.xacml.std.dom.DOMResponse;
75 import com.att.research.xacml.std.json.JSONRequest;
76 import com.att.research.xacml.std.json.JSONResponse;
77 import com.att.research.xacml.util.XACMLProperties;
78 import com.fasterxml.jackson.databind.ObjectMapper;
81 * Servlet implementation class XacmlPdpServlet
83 * This is an implementation of the XACML 3.0 RESTful Interface with added features to support
84 * simple PAP RESTful API for policy publishing and PIP configuration changes.
86 * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file.
87 * This properties file has all the default parameter settings. If you are running the servlet as is,
88 * then we recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever
89 * the default working directory is set to, a "config" directory will be created that holds the policy
90 * and pip cache. This setting is located in the xacml.pdp.properties file.
92 * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file
93 * system and setup the parameters as you wish. Just set the Java VM System variable to point to that file:
95 * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties
97 * Or if you only want to change one or two properties, simply set the Java VM System variable for that property.
99 * -Dxacml.rest.pdp.register=false
104 description = "Implements the XACML PDP RESTful API and client PAP API.",
105 urlPatterns = { "/" },
108 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.")
110 public class XACMLPdpServlet extends HttpServlet implements Runnable {
111 private static final long serialVersionUID = 1L;
112 private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767
113 private static final String CREATE_UPDATE_POLICY_SERVICE = "org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl";
115 // Our application debug log
117 private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class);
119 // This logger is specifically only for Xacml requests and their corresponding response.
120 // It's output ideally should be sent to a separate file from the application logger.
122 private static final Log requestLogger = LogFactory.getLog("xacml.request");
125 private static final Log auditLogger = LogFactory.getLog("auditLogger");
127 private static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton();
130 // This thread may getting invoked on startup, to let the PAP know
131 // that we are up and running.
133 private Thread registerThread = null;
134 private XACMLPdpRegisterThread registerRunnable = null;
136 // This is our PDP engine pointer. There is a synchronized lock used
137 // for access to the pointer. In case we are servicing PEP requests while
138 // an update is occurring from the PAP.
140 private static PDPEngine pdpEngine = null;
141 private static final Object pdpEngineLock = new Object();
143 // This is our PDP's status. What policies are loaded (or not) and
144 // what PIP configurations are loaded (or not).
145 // There is a synchronized lock used for access to the object.
147 private static volatile StdPDPStatus status = new StdPDPStatus();
148 private static final Object pdpStatusLock = new Object();
149 private static Constructor<?> createUpdatePolicyConstructor;
151 private static final String ENVIORNMENT_HEADER = "Environment";
152 private static String environment = null;
154 // Queue of PUT requests
156 public static class PutRequest {
157 private Properties policyProperties = null;
158 private Properties pipConfigProperties = null;
160 PutRequest(Properties policies, Properties pips) {
161 this.policyProperties = policies;
162 this.pipConfigProperties = pips;
165 public static volatile BlockingQueue<PutRequest> queue = null;
166 // For notification Delay.
167 private static int notificationDelay = 0;
168 public static int getNotificationDelay(){
169 return XACMLPdpServlet.notificationDelay;
172 private static String pdpResourceName;
173 private static String[] dependencyNodes = null;
176 // This is our configuration thread that attempts to load
177 // a new configuration request.
179 private Thread configThread = null;
180 private volatile boolean configThreadTerminate = false;
181 private ECOMPLoggingContext baseLoggingContext = null;
182 private IntegrityMonitor im;
184 * Default constructor.
186 public XACMLPdpServlet() {
187 //Default constructor.
191 * @see Servlet#init(ServletConfig)
194 public void init(ServletConfig config) throws ServletException {
195 String createUpdateResourceName = null;
196 String dependencyGroups = null;
200 XACMLRest.xacmlInit(config);
201 // Load the Notification Delay.
203 XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY));
205 logger.info("Notification Delay Not set. Keeping it 0 as default."+e);
208 int queueSize = 5; // Set default Queue Size here.
209 queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize)));
210 queue = new LinkedBlockingQueue<PutRequest>(queueSize);
211 // Load our engine - this will use the latest configuration
212 // that was saved to disk and set our initial status object.
214 PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null);
215 if (engine != null) {
216 synchronized(pdpEngineLock) {
223 baseLoggingContext = new ECOMPLoggingContext();
224 // fixed data that will be the same in all logging output goes here
226 String ipaddress = InetAddress.getLocalHost().getHostAddress();
227 baseLoggingContext.setServer(ipaddress);
228 } catch (UnknownHostException e) {
229 logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"+e);
232 Properties properties;
234 properties = XACMLProperties.getProperties();
235 } catch (IOException e) {
236 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e,
237 "Error loading properties with: XACMLProperties.getProperties()");
238 throw new ServletException(e.getMessage(), e.getCause());
240 if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){
241 XACMLProperties.reloadProperties();
243 properties = XACMLProperties.getProperties();
244 } catch (IOException e) {
245 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e,
246 "Error loading properties with: XACMLProperties.getProperties()");
247 throw new ServletException(e.getMessage(), e.getCause());
249 PolicyLogger.info("\n Properties Given : \n" + properties.toString());
251 pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME);
252 if(pdpResourceName == null){
253 PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
254 throw new ServletException("pdpResourceName is null");
257 dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
258 if(dependencyGroups == null){
259 PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp");
260 throw new ServletException("dependency_groups is null");
262 // dependency_groups is a semicolon-delimited list of groups, and
263 // each group is a comma-separated list of nodes. For our purposes
264 // we just need a list of dependencies without regard to grouping,
265 // so split the list into nodes separated by either comma or semicolon.
266 dependencyNodes = dependencyGroups.split("[;,]");
267 for (int i = 0 ; i < dependencyNodes.length ; i++){
268 dependencyNodes[i] = dependencyNodes[i].trim();
271 // CreateUpdatePolicy ResourceName
272 createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
273 setCreateUpdatePolicyConstructor(createUpdateResourceName);
275 // Create an IntegrityMonitor
277 logger.info("Creating IntegrityMonitor");
278 im = IntegrityMonitor.getInstance(pdpResourceName, properties);
279 } catch (Exception e) {
280 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor");
281 throw new ServletException(e);
284 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
286 // Kick off our thread to register with the PAP servlet.
288 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) {
289 this.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext);
290 this.registerThread = new Thread(this.registerRunnable);
291 this.registerThread.start();
294 // This is our thread that manages incoming configuration
297 this.configThread = new Thread(this);
298 this.configThread.start();
302 * @see Servlet#destroy()
305 public void destroy() {
307 logger.info("Destroying....");
309 // Make sure the register thread is not running
311 if (this.registerRunnable != null) {
313 this.registerRunnable.terminate();
314 if (this.registerThread != null) {
315 this.registerThread.interrupt();
316 this.registerThread.join();
318 } catch (InterruptedException e) {
319 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
320 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
324 // Make sure the configure thread is not running
326 this.configThreadTerminate = true;
328 this.configThread.interrupt();
329 this.configThread.join();
330 } catch (InterruptedException e) {
331 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
332 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
334 logger.info("Destroyed.");
338 * PUT - The PAP engine sends configuration information using HTTP PUT request.
340 * One parameter is expected:
342 * config=[policy|pip|all]
344 * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP should
345 * be using for PEP requests.
347 * Specifically should AT LEAST contain the following properties:
349 * xacml.referencedPolicies
351 * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache.
354 * xacml.rootPolicies=PolicyA.1, PolicyB.1
356 * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
357 * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
359 * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
361 * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
362 * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1
364 * pip - Expect a properties file that contain PIP engine configuration properties.
366 * Specifically should AT LEAST the following property:
369 * In addition, any relevant information needed by the PDP to load and configure the PIPs.
372 * xacml.pip.engines=foo,bar
374 * foo.classname=com.foo
379 * bar.classname=com.bar
382 * all - Expect ALL new configuration properties for the PDP
384 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
387 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
388 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
389 loggingContext.transactionStarted();
390 if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())){
391 UUID requestID = UUID.randomUUID();
392 loggingContext.setRequestID(requestID.toString());
393 PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one");
395 PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)");
397 loggingContext.metricStarted();
398 loggingContext.metricEnded();
399 PolicyLogger.metrics("Metric example posted here - 1 of 2");
400 loggingContext.metricStarted();
401 loggingContext.metricEnded();
402 PolicyLogger.metrics("Metric example posted here - 2 of 2");
404 // Dump our request out
406 if (logger.isDebugEnabled()) {
407 XACMLRest.dumpRequest(request);
411 im.startTransaction();
413 catch (AdministrativeStateException | StandbyStatusException e) {
414 String message = e.toString();
415 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e);
416 loggingContext.transactionEnded();
417 PolicyLogger.audit("Transaction Failed - See Error.log");
418 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
422 // What is being PUT?
424 String cache = request.getParameter("cache");
426 // Should be a list of policy and pip configurations in Java properties format
428 if (cache != null && request.getContentType().equals("text/x-java-properties")) {
429 loggingContext.setServiceName("PDP.putConfig");
430 if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) {
431 String message = "Content-Length larger than server will accept.";
432 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
433 loggingContext.transactionEnded();
434 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
435 PolicyLogger.audit("Transaction Failed - See Error.log");
436 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
440 this.doPutConfig(cache, request, response, loggingContext);
441 loggingContext.transactionEnded();
442 PolicyLogger.audit("Transaction ended");
446 String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'";
447 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
448 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
449 loggingContext.transactionEnded();
450 PolicyLogger.audit("Transaction Failed - See Error.log");
451 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
457 protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
459 // prevent multiple configuration changes from stacking up
460 if (XACMLPdpServlet.queue.remainingCapacity() <= 0) {
461 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached");
462 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached");
463 loggingContext.transactionEnded();
464 PolicyLogger.audit("Transaction Failed - See Error.log");
465 response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing.");
469 // Read the properties data into an object.
471 Properties newProperties = new Properties();
472 newProperties.load(request.getInputStream());
473 // should have something in the request
474 if (newProperties.size() == 0) {
475 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT");
476 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT");
477 loggingContext.transactionEnded();
478 PolicyLogger.audit("Transaction Failed - See Error.log");
479 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property");
483 // Which set of properties are they sending us? Whatever they send gets
484 // put on the queue (if there is room).
485 // For audit logging purposes, we consider the transaction done once the
486 // the request gets put on the queue.
488 if (config.equals("policies")) {
489 newProperties = XACMLProperties.getPolicyProperties(newProperties, true);
490 if (newProperties.size() == 0) {
491 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
492 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
493 loggingContext.transactionEnded();
494 PolicyLogger.audit("Transaction Failed - See Error.log");
495 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property");
498 XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null));
499 loggingContext.transactionEnded();
500 auditLogger.info("Success");
501 PolicyLogger.audit("Success");
502 } else if (config.equals("pips")) {
503 newProperties = XACMLProperties.getPipProperties(newProperties);
504 if (newProperties.size() == 0) {
505 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
506 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
507 loggingContext.transactionEnded();
508 PolicyLogger.audit("Transaction Failed - See Error.log");
509 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property");
512 XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties));
513 loggingContext.transactionEnded();
514 auditLogger.info("Success");
515 PolicyLogger.audit("Success");
516 } else if (config.equals("all")) {
517 Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true);
518 if (newPolicyProperties.size() == 0) {
519 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
520 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
521 loggingContext.transactionEnded();
522 PolicyLogger.audit("Transaction Failed - See Error.log");
523 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property");
526 Properties newPipProperties = XACMLProperties.getPipProperties(newProperties);
527 if (newPipProperties.size() == 0) {
528 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
529 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
530 loggingContext.transactionEnded();
531 PolicyLogger.audit("Transaction Failed - See Error.log");
532 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property");
535 XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties));
536 loggingContext.transactionEnded();
537 auditLogger.info("Success");
538 PolicyLogger.audit("Success");
543 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config);
544 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config);
545 loggingContext.transactionEnded();
546 PolicyLogger.audit("Transaction Failed - See Error.log");
547 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'");
550 } catch (Exception e) {
551 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e);
552 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration");
553 loggingContext.transactionEnded();
554 PolicyLogger.audit("Transaction Failed - See Error.log");
555 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
562 * Parameters: type=hb|config|Status
564 * 1. HeartBeat Status
566 * OK - All Policies are Loaded, All PIPs are Loaded
567 * LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration
568 * LAST_UPDATE_FAILED - Need to track the items that failed during last update
569 * LOAD_FAILURE - ??? Need to determine what information is sent and how
572 * return the StdPDPStatus object in the Response content
575 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
578 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
579 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
580 loggingContext.transactionStarted();
581 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
582 UUID requestID = UUID.randomUUID();
583 loggingContext.setRequestID(requestID.toString());
584 PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one");
586 PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)");
588 loggingContext.metricStarted();
589 loggingContext.metricEnded();
590 PolicyLogger.metrics("Metric example posted here - 1 of 2");
591 loggingContext.metricStarted();
592 loggingContext.metricEnded();
593 PolicyLogger.metrics("Metric example posted here - 2 of 2");
595 XACMLRest.dumpRequest(request);
597 String pathInfo = request.getRequestURI();
598 if (pathInfo != null){
599 // health check from Global Site Selector (iDNS).
600 // DO NOT do a im.startTransaction for the test request
601 if (pathInfo.equals("/pdp/test")) {
602 loggingContext.setServiceName("iDNS:PDP.test");
605 //If we make it this far, all is well
606 String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
607 PolicyLogger.debug(message);
608 loggingContext.transactionEnded();
609 PolicyLogger.audit("Success");
610 response.setStatus(HttpServletResponse.SC_OK);
612 } catch (ForwardProgressException fpe){
613 //No forward progress is being made
614 String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress."
615 + " Exception Message: " + fpe.getMessage();
616 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
617 loggingContext.transactionEnded();
618 PolicyLogger.audit("Transaction Failed - See Error.log");
619 // PolicyLogger.audit(MessageCodes.ERROR_SYSTEM_ERROR, message );
620 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
622 }catch (AdministrativeStateException ase){
623 //Administrative State is locked
624 String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED "
625 + " Exception Message: " + ase.getMessage();
626 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
627 loggingContext.transactionEnded();
628 PolicyLogger.audit("Transaction Failed - See Error.log");
629 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
631 }catch (StandbyStatusException sse){
632 //Administrative State is locked
633 String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE "
634 + " Exception Message: " + sse.getMessage();
635 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
636 loggingContext.transactionEnded();
637 PolicyLogger.audit("Transaction Failed - See Error.log");
638 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
640 } catch (Exception e) {
641 //A subsystem is not making progress or is not responding
642 String eMsg = e.getMessage();
644 eMsg = "No Exception Message";
646 String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
647 + " Exception Message: " + eMsg;
648 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
649 //Get the specific list of subsystems that failed
650 String failedNodeList = null;
651 for(String node : dependencyNodes){
652 if(eMsg.contains(node)){
653 if(failedNodeList == null){
654 failedNodeList = node;
656 failedNodeList = failedNodeList.concat(","+node);
660 if(failedNodeList == null){
661 failedNodeList = "UnknownSubSystem";
663 response.addHeader("X-ECOMP-SubsystemFailure", failedNodeList);
664 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
665 loggingContext.transactionEnded();
666 PolicyLogger.audit("Transaction Failed - See Error.log");
673 im.startTransaction();
675 catch (AdministrativeStateException | StandbyStatusException e) {
676 String message = e.toString();
677 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
678 loggingContext.transactionEnded();
679 PolicyLogger.audit("Transaction Failed - See Error.log");
680 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
684 // What are they requesting?
686 boolean returnHB = false;
687 response.setHeader("Cache-Control", "no-cache");
688 String type = request.getParameter("type");
689 // type might be null, so use equals on string constants
690 if ("config".equals(type)) {
691 loggingContext.setServiceName("PDP.getConfig");
692 response.setContentType("text/x-java-properties");
694 String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
695 lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n";
696 try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes());
697 InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig());
698 OutputStream os = response.getOutputStream()) {
699 IOUtils.copy(listInputStream, os);
700 IOUtils.copy(pipInputStream, os);
702 loggingContext.transactionEnded();
703 auditLogger.info("Success");
704 PolicyLogger.audit("Success");
705 response.setStatus(HttpServletResponse.SC_OK);
706 } catch (Exception e) {
707 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e);
708 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file");
709 loggingContext.transactionEnded();
710 PolicyLogger.audit("Transaction Failed - See Error.log");
711 response.sendError(400, "Failed to copy Property file");
714 } else if ("hb".equals(type)) {
716 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
718 } else if ("Status".equals(type)) {
719 loggingContext.setServiceName("PDP.getStatus");
720 // convert response object to JSON and include in the response
721 synchronized(pdpStatusLock) {
722 ObjectMapper mapper = new ObjectMapper();
723 mapper.writeValue(response.getOutputStream(), status);
725 response.setStatus(HttpServletResponse.SC_OK);
726 loggingContext.transactionEnded();
727 auditLogger.info("Success");
728 PolicyLogger.audit("Success");
731 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type);
732 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type);
733 loggingContext.transactionEnded();
734 PolicyLogger.audit("Transaction Failed - See Error.log");
735 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'");
738 synchronized(pdpStatusLock) {
739 response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
742 loggingContext.transactionEnded();
743 PolicyLogger.audit("Transaction Ended");
749 * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according
750 * to the XACML 3.0 Specifications for both.
753 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
756 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
758 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
759 loggingContext.transactionStarted();
760 loggingContext.setServiceName("PDP.decide");
761 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
762 UUID requestID = UUID.randomUUID();
763 loggingContext.setRequestID(requestID.toString());
764 PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one");
766 PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)");
768 loggingContext.metricStarted();
769 loggingContext.metricEnded();
770 PolicyLogger.metrics("Metric example posted here - 1 of 2");
771 loggingContext.metricStarted();
772 loggingContext.metricEnded();
773 PolicyLogger.metrics("Metric example posted here - 2 of 2");
774 monitor.pdpEvaluationAttempts();
777 im.startTransaction();
779 catch (AdministrativeStateException | StandbyStatusException e) {
780 String message = e.toString();
781 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e);
782 loggingContext.transactionEnded();
783 PolicyLogger.audit("Transaction Failed - See Error.log");
784 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
788 // no point in doing any work if we know from the get-go that we cannot do anything with the request
790 if (status.getLoadedRootPolicies().isEmpty()) {
791 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
792 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
793 loggingContext.transactionEnded();
794 PolicyLogger.audit("Transaction Failed - See Error.log");
795 response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
800 XACMLRest.dumpRequest(request);
802 // Set our no-cache header
804 response.setHeader("Cache-Control", "no-cache");
806 // They must send a Content-Type
808 if (request.getContentType() == null) {
809 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type");
810 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type");
811 loggingContext.transactionEnded();
812 PolicyLogger.audit("Transaction Failed - See Error.log");
813 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
818 // Limit the Content-Length to something reasonable
820 if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
821 String message = "Content-Length larger than server will accept.";
822 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
823 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
824 loggingContext.transactionEnded();
825 PolicyLogger.audit("Transaction Failed - See Error.log");
826 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
830 if (request.getContentLength() <= 0) {
831 String message = "Content-Length is negative";
832 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
833 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
834 loggingContext.transactionEnded();
835 PolicyLogger.audit("Transaction Failed - See Error.log");
836 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
840 ContentType contentType = null;
842 contentType = ContentType.parse(request.getContentType());
844 catch (Exception e) {
845 String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
846 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e);
847 loggingContext.transactionEnded();
848 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message);
849 PolicyLogger.audit("Transaction Failed - See Error.log");
850 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
855 // What exactly did they send us?
857 String incomingRequestString = null;
858 Request pdpRequest = null;
859 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) ||
860 contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
861 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) {
863 // Read in the string
865 StringBuilder buffer = new StringBuilder();
866 BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
869 while((line = reader.readLine()) != null){
873 logger.error("Exception Occured while reading line"+e);
876 incomingRequestString = buffer.toString();
877 logger.info(incomingRequestString);
879 // Parse into a request
882 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
883 pdpRequest = JSONRequest.load(incomingRequestString);
884 } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
885 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
886 pdpRequest = DOMRequest.load(incomingRequestString);
890 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e);
891 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request");
892 loggingContext.transactionEnded();
893 PolicyLogger.audit("Transaction Failed - See Error.log");
894 response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
899 String message = "unsupported content type" + request.getContentType();
900 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
901 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
902 loggingContext.transactionEnded();
903 PolicyLogger.audit("Transaction Failed - See Error.log");
904 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
909 // Did we successfully get and parse a request?
911 if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) {
912 String message = "Zero Attributes found in the request";
913 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
914 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
915 loggingContext.transactionEnded();
916 PolicyLogger.audit("Transaction Failed - See Error.log");
917 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
926 // Authenticating the Request here.
928 if(!authorizeRequest(request)){
929 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
930 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
931 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message);
932 loggingContext.transactionEnded();
933 PolicyLogger.audit("Transaction Failed - See Error.log");
934 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
939 // Get the pointer to the PDP Engine
941 PDPEngine myEngine = null;
942 synchronized(pdpEngineLock) {
943 myEngine = XACMLPdpServlet.pdpEngine;
945 if (myEngine == null) {
946 String message = "No engine loaded.";
947 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
948 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
949 loggingContext.transactionEnded();
950 PolicyLogger.audit("Transaction Failed - See Error.log");
951 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
956 // Send the request and save the response
960 Response pdpResponse = null;
962 synchronized(pdpEngineLock) {
963 myEngine = XACMLPdpServlet.pdpEngine;
965 PolicyList.clearPolicyList();
966 lTimeStart = System.currentTimeMillis();
967 pdpResponse = myEngine.decide(pdpRequest);
968 lTimeEnd = System.currentTimeMillis();
969 } catch (PDPException e) {
970 String message = "Exception during decide: " + e.getMessage();
971 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e);
972 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
973 loggingContext.transactionEnded();
974 PolicyLogger.audit("Transaction Failed - See Error.log");
975 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
980 monitor.computeLatency(lTimeEnd - lTimeStart);
981 requestLogger.info(lTimeStart + "=" + incomingRequestString);
982 for(String policy : PolicyList.getpolicyList()){
983 monitor.policyCountAdd(policy, 1);
987 logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList());
989 //need to go through the list and find out if the value is unique and then add it other wise
990 // monitor.policyCountAdd(PolicyList.getpolicyList(), 1);
992 if (logger.isDebugEnabled()) {
993 logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
996 // Convert Response to appropriate Content-Type
998 if (pdpResponse == null) {
999 requestLogger.info(lTimeStart + "=" + "{}");
1000 throw new PDPException("Failed to get response from PDP engine.");
1003 // Set our content-type
1005 response.setContentType(contentType.getMimeType());
1007 // Convert the PDP response object to a String to
1008 // return to our caller as well as dump to our loggers.
1010 String outgoingResponseString = "";
1011 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
1013 // Get it as a String. This is not very efficient but we need to log our
1014 // results for auditing.
1016 outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
1017 if (logger.isDebugEnabled()) {
1018 logger.debug(outgoingResponseString);
1020 // Get rid of whitespace
1022 outgoingResponseString = JSONResponse.toString(pdpResponse, false);
1024 } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
1025 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
1027 // Get it as a String. This is not very efficient but we need to log our
1028 // results for auditing.
1030 outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
1031 if (logger.isDebugEnabled()) {
1032 logger.debug(outgoingResponseString);
1034 // Get rid of whitespace
1036 outgoingResponseString = DOMResponse.toString(pdpResponse, false);
1039 // adding the jmx values for NA, Permit and Deny
1041 if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){
1042 monitor.pdpEvaluationNA();
1045 if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){
1046 monitor.pdpEvaluationPermit();
1049 if (outgoingResponseString.contains("Deny")){
1050 monitor.pdpEvaluationDeny();
1053 // lTimeStart is used as an ID within the requestLogger to match up
1054 // request's with responses.
1056 requestLogger.info(lTimeStart + "=" + outgoingResponseString);
1057 response.getWriter().print(outgoingResponseString);
1059 catch (Exception e) {
1060 String message = "Exception executing request: " + e;
1061 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e);
1062 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message);
1063 loggingContext.transactionEnded();
1064 PolicyLogger.audit("Transaction Failed - See Error.log");
1065 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1069 monitor.pdpEvaluationSuccess();
1070 response.setStatus(HttpServletResponse.SC_OK);
1072 loggingContext.transactionEnded();
1073 auditLogger.info("Success");
1074 PolicyLogger.audit("Success");
1079 * Added for Authorizing the PEP Requests for Environment check.
1081 private boolean authorizeRequest(HttpServletRequest request) {
1082 // Get the client Credentials from the Request header.
1083 HttpServletRequest httpServletRequest = request;
1084 String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER);
1085 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
1095 // Keep running until we are told to terminate
1098 // variable not used, but constructor has needed side-effects so don't remove:
1099 while (! this.configThreadTerminate) {
1100 PutRequest request = XACMLPdpServlet.queue.take();
1101 StdPDPStatus newStatus = new StdPDPStatus();
1103 PDPEngine newEngine = null;
1104 synchronized(pdpStatusLock) {
1105 XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION);
1106 newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties);
1108 if (newEngine != null) {
1109 synchronized(XACMLPdpServlet.pdpEngineLock) {
1110 XACMLPdpServlet.pdpEngine = newEngine;
1112 logger.info("Saving configuration.");
1113 if (request.policyProperties != null) {
1114 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) {
1115 request.policyProperties.store(os, "");
1118 if (request.pipConfigProperties != null) {
1119 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) {
1120 request.pipConfigProperties.store(os, "");
1123 newStatus.setStatus(Status.UP_TO_DATE);
1124 } catch (Exception e) {
1125 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e);
1126 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties");
1127 newStatus.setStatus(Status.LOAD_ERRORS);
1128 newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage());
1132 newStatus.setStatus(Status.LAST_UPDATE_FAILED);
1134 synchronized(pdpStatusLock) {
1135 XACMLPdpServlet.status.set(newStatus);
1138 } catch (InterruptedException e) {
1139 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e);
1140 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted");
1141 Thread.currentThread().interrupt();
1145 public static PDPEngine getPDPEngine(){
1146 PDPEngine myEngine = null;
1147 synchronized(pdpEngineLock) {
1148 myEngine = XACMLPdpServlet.pdpEngine;
1153 public static Constructor<?> getCreateUpdatePolicyConstructor(){
1154 return createUpdatePolicyConstructor;
1157 private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{
1159 Class<?> createUpdateclass = Class.forName(createUpdateResourceName);
1160 createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class);
1161 }catch(Exception e){
1162 PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init");
1163 throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage());