2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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.onap.policy.pap.xacml.rest;
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.api.pap.PDPStatus;
26 import com.att.research.xacml.util.FactoryException;
27 import com.att.research.xacml.util.XACMLProperties;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.google.common.base.Splitter;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.net.InetAddress;
37 import java.net.UnknownHostException;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.util.List;
42 import java.util.Properties;
44 import java.util.UUID;
45 import java.util.concurrent.CopyOnWriteArrayList;
47 import javax.persistence.PersistenceException;
48 import javax.servlet.Servlet;
49 import javax.servlet.ServletConfig;
50 import javax.servlet.ServletException;
51 import javax.servlet.annotation.WebInitParam;
52 import javax.servlet.annotation.WebServlet;
53 import javax.servlet.http.HttpServlet;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
57 import org.apache.commons.io.IOUtils;
58 import org.onap.policy.common.ia.IntegrityAudit;
59 import org.onap.policy.common.im.AdministrativeStateException;
60 import org.onap.policy.common.im.ForwardProgressException;
61 import org.onap.policy.common.im.IntegrityMonitor;
62 import org.onap.policy.common.im.IntegrityMonitorException;
63 import org.onap.policy.common.im.IntegrityMonitorProperties;
64 import org.onap.policy.common.im.StandbyStatusException;
65 import org.onap.policy.common.logging.OnapLoggingContext;
66 import org.onap.policy.common.logging.OnapLoggingUtils;
67 import org.onap.policy.common.logging.eelf.MessageCodes;
68 import org.onap.policy.common.logging.eelf.PolicyLogger;
69 import org.onap.policy.common.logging.flexlogger.FlexLogger;
70 import org.onap.policy.common.logging.flexlogger.Logger;
71 import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications;
72 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
73 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
74 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
75 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
76 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
77 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
78 import org.onap.policy.rest.XacmlRest;
79 import org.onap.policy.rest.XacmlRestProperties;
80 import org.onap.policy.rest.dao.PolicyDBException;
81 import org.onap.policy.utils.PeCryptoUtils;
82 import org.onap.policy.utils.PolicyUtils;
83 import org.onap.policy.xacml.api.XACMLErrorConstants;
84 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
85 import org.onap.policy.xacml.api.pap.OnapPDP;
86 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
87 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
88 import org.onap.policy.xacml.std.pap.StdPDP;
89 import org.onap.policy.xacml.std.pap.StdPDPGroup;
90 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
91 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
92 import org.onap.policy.xacml.std.pap.StdPDPStatus;
95 * Servlet implementation class XacmlPapServlet.
98 description = "Implements the XACML PAP RESTful API.",
101 initParams = {@WebInitParam(
102 name = "XACML_PROPERTIES_NAME",
103 value = "xacml.pap.properties",
104 description = "The location of the properties file holding configuration information.")})
105 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
106 private static final long serialVersionUID = 1L;
107 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
108 // audit (transaction) LOGGER
109 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
110 // Persistence Unit for JPA
111 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
112 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
114 private static final String ENVIRONMENT_HEADER = "Environment";
115 private static final String ADD_GROUP_ERROR = "addGroupError";
116 private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
118 private static final String REGEX = "[0-9a-zA-Z._ ]*";
121 * List of Admin Console URLs. Used to send notifications when configuration changes.
123 * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom
124 * changed but often read, so the costs of this approach make sense.
126 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
128 private static String configHome;
129 private static String actionHome;
131 * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET
132 * the Policy files from this process.
134 private static String papUrl = null;
135 // The heartbeat thread.
136 private static Heartbeat heartbeat = null;
137 private static Thread heartbeatThread = null;
138 private static PolicyDBDao policyDbDao;
140 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
142 private static PAPPolicyEngine papEngine = null;
144 * These are the parameters needed for DB access from the PAP
146 private static int papIntegrityAuditPeriodSeconds = -1;
147 private static String papDbDriver = null;
148 private static String papDbUrl = null;
149 private static String papDbUser = null;
150 private static String papDbPd = null;
151 private static String papResourceName = null;
152 private static String[] papDependencyGroupsFlatArray = null;
153 private static String environment = null;
154 private static String pdpFile = null;
156 private transient IntegrityMonitor im;
157 private transient IntegrityAudit ia;
159 // MicroService Model Properties
160 private static String msOnapName;
161 private static String msPolicyName;
163 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
164 * this servlet starts. Its configurable by the admin.
166 private static transient Thread initiateThread = null;
167 private transient OnapLoggingContext baseLoggingContext = null;
168 private static final String GROUPID = "groupId";
171 * @see HttpServlet#HttpServlet()
173 public XACMLPapServlet() {
178 * @see Servlet#init(ServletConfig)
181 public void init(ServletConfig config) throws ServletException {
184 baseLoggingContext = new OnapLoggingContext();
185 // fixed data that will be the same in all logging output goes here
187 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
188 baseLoggingContext.setServer(hostname);
189 } catch (UnknownHostException e) {
190 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
194 XacmlRest.xacmlInit(config);
195 // Load the properties
196 XacmlRest.loadXacmlProperties(null, null);
198 * Retrieve the property values
200 setCommonProperties();
201 String papSiteName = XACMLProperties.getProperty(XacmlRestProperties.PAP_SITE_NAME);
202 if (papSiteName == null) {
203 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
204 " ERROR: Bad papSiteName property entry");
205 throw new PAPException("papSiteName is null");
207 String papNodeType = XACMLProperties.getProperty(XacmlRestProperties.PAP_NODE_TYPE);
208 if (papNodeType == null) {
209 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
210 " ERROR: Bad papNodeType property entry");
211 throw new PAPException("papNodeType is null");
213 // Integer will throw an exception of anything is missing or
215 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
216 int papTransTimeout =
217 Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT));
218 int papAuditTimeout =
219 Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
220 // Boolean will default to false if anything is missing or
222 boolean papAuditFlag =
223 Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
224 boolean papFileSystemAudit =
225 Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_FLAG));
226 String papDependencyGroups = XACMLProperties.getProperty(XacmlRestProperties.PAP_DEPENDENCY_GROUPS);
227 if (papDependencyGroups == null) {
228 throw new PAPException("papDependencyGroups is null");
230 setPAPDependencyGroups(papDependencyGroups);
231 // Integer will throw an exception of anything is missing or
233 int fpMonitorInterval =
234 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
235 int failedCounterThreshold =
236 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
237 int testTransInterval =
238 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
239 int writeFpcInterval =
240 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
241 LOGGER.debug("\n\n\n**************************************" + "\n*************************************"
242 + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = "
243 + papDbUser + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout
244 + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag
245 + "\n papFileSystemAudit = " + papFileSystemAudit + "\n papResourceName = " + papResourceName
246 + "\n fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = "
247 + failedCounterThreshold + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = "
248 + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + papNodeType
249 + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = "
250 + papIntegrityAuditPeriodSeconds + "\n\n*************************************"
251 + "\n**************************************");
252 // Pull custom persistence settings
253 Properties properties;
255 properties = XACMLProperties.getProperties();
256 LOGGER.debug("\n\n\n**************************************" + "\n**************************************"
257 + "\n\n" + "properties = " + properties + "\n\n**************************************");
258 } catch (IOException e) {
259 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet",
260 " Error loading properties with: " + "XACMLProperties.getProperties()");
261 throw new ServletException(e.getMessage(), e.getCause());
263 // Create an IntegrityMonitor
264 if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
265 properties.setProperty(PERSISTENCE_JDBC_PWD,
266 PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
268 im = IntegrityMonitor.getInstance(papResourceName, properties);
269 // Create an IntegrityAudit
270 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
271 ia.startAuditThread();
272 // we are about to call the PDPs and give them their configuration.
273 // To do that we need to have the URL of this PAP so we can
274 // construct the Policy file URLs
275 setPapUrl(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL));
276 // Create the policyDBDao
278 // Load our PAP engine, first create a factory
279 ONAPPapEngineFactory factory = ONAPPapEngineFactory
280 .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
281 // The factory knows how to go about creating a PAP Engine
282 setPAPEngine(factory.newEngine());
283 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
284 createDefaultGroupOnInit();
286 policyDbDao.setPapEngine(XACMLPapServlet.papEngine);
287 if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
289 * Auditing the local File System groups to be in sync with the Database
292 // get an AuditTransaction to lock out all other transactions
293 PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
295 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
296 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
297 // get the current filesystem group and update from the database
299 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
300 StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group);
301 if (updatedGroup != null) {
302 papEngine.updateGroup(updatedGroup);
304 LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
306 // sync up the config data from DB to file system
307 LOGGER.info("PapServlet: Sync config data from DB to file system");
308 policyDbDao.synchronizeConfigDataInFileSystem();
310 // release the transaction lock
314 // Configurable - have the PAP servlet initiate sending the latest
315 // PDP policy/pip configuration
316 // to all its known PDP nodes.
317 if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
318 startInitiateThreadService(new Thread(this));
320 // After startup, the PAP does Heartbeat's to each of the PDPs
322 startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine));
323 } catch (FactoryException | PAPException e) {
324 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
325 throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e);
326 } catch (Exception e) {
327 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
328 " Failed to create engine - unexpected error");
329 throw new ServletException(
330 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e);
335 private void createDefaultGroupOnInit() {
336 PolicyDBDaoTransaction addNewGroup = null;
338 addNewGroup = policyDbDao.getNewTransaction();
339 OnapPDPGroup group = papEngine.getDefaultGroup();
340 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
341 addNewGroup.commitTransaction();
342 addNewGroup = policyDbDao.getNewTransaction();
343 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
344 addNewGroup.commitTransaction();
345 } catch (Exception e) {
346 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
347 " Error creating new default group in the database");
348 if (addNewGroup != null) {
349 addNewGroup.rollbackTransaction();
354 private static void startInitiateThreadService(Thread thread) {
355 initiateThread = thread;
356 initiateThread.start();
359 private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
361 mapper.writeValue(response.getOutputStream(), value);
362 } catch (Exception e) {
367 private static void startHeartBeatService(Heartbeat heartbeat) {
368 XACMLPapServlet.heartbeat = heartbeat;
369 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
370 XACMLPapServlet.heartbeatThread.start();
373 private static void setPolicyDbDao() throws ServletException {
375 policyDbDao = PolicyDBDao.getPolicyDBDaoInstance();
376 } catch (Exception e) {
377 throw new ServletException("Unable to Create Policy DBDao Instance", e);
381 public static PolicyDBDao getPolicyDbDao() {
385 private static void setPapUrl(String papUrl) {
386 XACMLPapServlet.papUrl = papUrl;
389 public static String getPapUrl() {
393 private static void setPAPEngine(PAPPolicyEngine newEngine) {
394 XACMLPapServlet.papEngine = newEngine;
397 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
399 // Now we have flattened the array into a simple comma-separated list
400 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
401 // clean up the entries
402 for (int i = 0; i < papDependencyGroupsFlatArray.length; i++) {
403 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
406 if (XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) {
407 papIntegrityAuditPeriodSeconds = Integer.parseInt(
408 XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
410 } catch (Exception e) {
411 String msg = "integrity_audit_period_seconds ";
412 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
413 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
414 " ERROR: " + msg + "Bad property entry");
417 } catch (Exception e) {
418 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
419 throw new PAPException(e);
423 private static void setCommonProperties() throws PAPException {
426 papDbDriver = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_DRIVER);
427 if (papDbDriver == null) {
428 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
429 " ERROR: Bad papDbDriver property entry");
430 throw new PAPException("papDbDriver is null");
432 setPapDbDriver(papDbDriver);
433 papDbUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_URL);
434 if (papDbUrl == null) {
435 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
436 throw new PAPException("papDbUrl is null");
438 setPapDbUrl(papDbUrl);
439 papDbUser = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_USER);
440 if (papDbUser == null) {
441 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
442 " ERROR: Bad papDbUser property entry");
443 throw new PAPException("papDbUser is null");
445 setPapDbUser(papDbUser);
446 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
447 papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_PASSWORD));
448 if (papDbPd == null) {
449 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
450 " ERROR: Bad papDbPassword property entry");
451 throw new PAPException("papDbPassword is null");
453 setPapDbPassword(papDbPd);
454 papResourceName = XACMLProperties.getProperty(XacmlRestProperties.PAP_RESOURCE_NAME);
455 if (papResourceName == null) {
456 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
457 " ERROR: Bad papResourceName property entry");
458 throw new PAPException("papResourceName is null");
460 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
461 // Micro Service Properties
462 msOnapName = XACMLProperties.getProperty("xacml.policy.msOnapName");
463 setMsOnapName(msOnapName);
464 msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName");
465 setMsPolicyName(msPolicyName);
466 // PDPId File location
467 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
468 if (XACMLPapServlet.pdpFile == null) {
469 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
470 + XacmlRestProperties.PROP_PDP_IDFILE);
471 throw new PAPException("The PDP Id Authentication File Property :" + XacmlRestProperties.PROP_PDP_IDFILE
472 + " is not Valid. ");
477 * Thread used only during PAP startup to initiate change messages to all known PDPs. This must
478 * be on a separate thread so that any GET requests from the PDPs during this update can be
483 // send the current configuration to all the PDPs that we know about
488 * @see Servlet#destroy()
490 * Depending on how this servlet is run, we may or may not care about cleaning up the
491 * resources. For now we assume that we do care.
494 public void destroy() {
495 // Make sure our threads are destroyed
496 if (XACMLPapServlet.heartbeatThread != null) {
497 // stop the heartbeat
499 if (XACMLPapServlet.heartbeat != null) {
500 XACMLPapServlet.heartbeat.terminate();
502 XACMLPapServlet.heartbeatThread.interrupt();
503 XACMLPapServlet.heartbeatThread.join();
504 } catch (InterruptedException e) {
505 XACMLPapServlet.heartbeatThread.interrupt();
506 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
509 if (initiateThread != null) {
511 initiateThread.interrupt();
512 initiateThread.join();
513 } catch (InterruptedException e) {
514 initiateThread.interrupt();
515 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
520 private ConsoleAndApiService getAcServiceInstance() {
521 return new ConsoleAndApiService();
525 * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make
526 * changes in the PDP Groups.
528 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
531 protected void doPost(HttpServletRequest request, HttpServletResponse response)
532 throws ServletException, IOException {
533 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
534 setLoggingContext(loggingContext, "doPost", "PAP.post");
535 PolicyDBDaoTransaction pdpTransaction = null;
537 loggingContext.metricStarted();
538 im.startTransaction();
539 loggingContext.metricEnded();
540 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
541 } catch (AdministrativeStateException ae) {
542 String message = "POST interface called for PAP " + papResourceName
543 + " but it has an Administrative state of " + im.getStateManager().getAdminState()
544 + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
545 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
546 loggingContext.metricEnded();
547 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
548 loggingContext.transactionEnded();
549 PolicyLogger.audit("Transaction Failed - See Error.log");
550 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
552 } catch (IntegrityMonitorException ime) {
554 "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
555 + im.getStateManager().getAdminState() + " and a Standby Status of "
556 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
557 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime);
558 loggingContext.metricEnded();
559 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
560 loggingContext.transactionEnded();
561 PolicyLogger.audit("Transaction Failed - See Error.log");
562 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
566 loggingContext.metricStarted();
567 XacmlRest.dumpRequest(request);
568 loggingContext.metricEnded();
569 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
570 // since getParameter reads the content string, explicitly get the
571 // content before doing that.
572 // Simply getting the inputStream seems to protect it against being
573 // consumed by getParameter.
574 request.getInputStream();
575 String groupId = request.getParameter(GROUPID);
576 String apiflag = request.getParameter("apiflag");
577 if (groupId != null) {
578 // Is this from the Admin Console or API?
579 if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
580 // this is from the API so we need to check the client
581 // credentials before processing the request
582 if (!authorizeRequest(request)) {
583 String message = "PEP not Authorized for making this Request!!";
584 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
585 loggingContext.transactionEnded();
586 PolicyLogger.audit("Transaction Failed - See Error.log");
587 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
592 loggingContext.metricStarted();
593 getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine);
594 loggingContext.metricEnded();
595 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
596 loggingContext.transactionEnded();
597 PolicyLogger.audit("Transaction Ended Successfully");
601 // Request is from a PDP asking for its config.
602 loggingContext.setServiceName("PDP:PAP.register");
604 String id = this.getPDPID(request);
605 String jmxport = this.getPDPJMX(request);
606 LOGGER.info("Request(doPost) from PDP coming up: " + id);
607 // Get the PDP Object
608 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
611 LOGGER.info("Unknown PDP: " + id);
613 if (CheckPDP.validateID(id)) {
614 pdpTransaction = policyDbDao.getNewTransaction();
616 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id,
617 "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
618 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id,
619 "Registered on first startup", Integer.parseInt(jmxport));
620 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException
621 | PersistenceException | PolicyDBException e) {
622 pdpTransaction.rollbackTransaction();
623 String message = "Failed to create new PDP for id: " + id;
624 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
625 loggingContext.transactionEnded();
626 PolicyLogger.audit("Transaction Failed - See Error.log");
627 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
631 // get the PDP we just created
633 pdp = XACMLPapServlet.papEngine.getPDP(id);
634 } catch (PAPException e) {
638 if (pdpTransaction != null) {
639 pdpTransaction.rollbackTransaction();
641 String message = "Failed to create new PDP for id: " + id;
642 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
643 loggingContext.transactionEnded();
644 PolicyLogger.audit("Transaction Failed - See Error.log");
645 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
650 String message = "PDP is Unauthorized to Connect to PAP: " + id;
651 loggingContext.transactionEnded();
652 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
653 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
654 "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
655 PolicyLogger.audit("Transaction Failed - See Error.log");
660 loggingContext.metricStarted();
661 pdpTransaction.commitTransaction();
662 loggingContext.metricEnded();
663 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
664 } catch (Exception e) {
665 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
666 "Could not commit transaction to put pdp in the database");
669 if (jmxport != null && !"".equals(jmxport)) {
671 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
672 } catch (NumberFormatException e) {
676 // Get the PDP's Group
677 OnapPDPGroup group = null;
679 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
680 } catch (PAPException e) {
685 MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
686 loggingContext.transactionEnded();
687 PolicyLogger.audit("Transaction Failed - See Error.log");
688 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
689 "PDP not associated with any group, even the default");
693 // Determine what group the PDP node is in and get
694 // its policy/pip properties.
695 Properties policies = group.getPolicyProperties();
696 Properties pipconfig = group.getPipConfigProperties();
697 // Get the current policy/pip configuration that the PDP has
698 Properties pdpProperties = new Properties();
700 pdpProperties.load(request.getInputStream());
701 } catch (IOException e) {
704 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
705 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
706 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
707 // Validate the node's properties
708 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
709 // Send back current configuration
711 // Tell the PDP we are sending back the current policies/pip
713 LOGGER.info("PDP configuration NOT current.");
714 if (policies != null) {
715 // Put URL's into the properties in case the PDP needs to
717 this.populatePolicyURL(request.getRequestURL(), policies);
718 // Copy the properties to the output stream
720 policies.store(response.getOutputStream(), "");
721 } catch (IOException e) {
725 if (pipconfig != null) {
726 // Copy the properties to the output stream
728 pipconfig.store(response.getOutputStream(), "");
729 } catch (IOException e) {
733 // We are good - and we are sending them information
734 response.setStatus(HttpServletResponse.SC_OK);
736 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
737 } catch (PAPException e) {
741 // Tell them they are good
742 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
744 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
745 } catch (PAPException e) {
749 auditLogger.info("Success");
750 PolicyLogger.audit("Transaction Ended Successfully");
751 } catch (PAPException | IOException | NumberFormatException e) {
752 if (pdpTransaction != null) {
753 pdpTransaction.rollbackTransaction();
755 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
756 loggingContext.transactionEnded();
757 PolicyLogger.audit("Transaction Failed - See Error.log");
758 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
762 // Catch anything that fell through
763 loggingContext.transactionEnded();
764 PolicyLogger.audit("Transaction Ended");
768 private void setResponseError(HttpServletResponse response, int responseCode, String message) {
770 if (message != null && !message.isEmpty()) {
771 response.sendError(responseCode, message);
773 } catch (IOException e) {
774 LOGGER.error("Error setting Error response Header ", e);
779 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
782 protected void doGet(HttpServletRequest request, HttpServletResponse response)
783 throws ServletException, IOException {
784 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
785 setLoggingContext(loggingContext, "doGet", "PAP.get");
786 loggingContext.metricStarted();
787 XacmlRest.dumpRequest(request);
788 loggingContext.metricEnded();
789 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
790 String pathInfo = request.getRequestURI();
791 LOGGER.info("path info: " + pathInfo);
792 if (pathInfo != null && "/pap/test".equals(pathInfo)) {
793 // DO NOT do a im.startTransaction for the test request
795 testService(loggingContext, response);
796 } catch (IOException e) {
801 // This im.startTransaction() covers all other Get transactions
803 loggingContext.metricStarted();
804 im.startTransaction();
805 loggingContext.metricEnded();
806 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
807 } catch (IntegrityMonitorException ime) {
809 "GET interface called for PAP " + papResourceName + " but it has an Administrative state of "
810 + im.getStateManager().getAdminState() + " and a Standby Status of "
811 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
812 LOGGER.info(message, ime);
813 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
814 loggingContext.transactionEnded();
815 PolicyLogger.audit("Transaction Failed - See Error.log");
816 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
819 // Request from the API to get the gitPath
820 String apiflag = request.getParameter("apiflag");
821 if (apiflag != null) {
822 if (authorizeRequest(request)) {
823 APIRequestHandler apiRequestHandler = new APIRequestHandler();
825 loggingContext.metricStarted();
826 apiRequestHandler.doGet(request, response, apiflag);
827 loggingContext.metricEnded();
828 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
829 } catch (IOException e) {
832 loggingContext.transactionEnded();
833 PolicyLogger.audit("Transaction Ended Successfully");
838 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
839 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
840 loggingContext.transactionEnded();
841 PolicyLogger.audit("Transaction Failed - See Error.log");
842 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
847 // Is this from the Admin Console?
848 String groupId = request.getParameter(GROUPID);
849 if (groupId != null) {
850 // this is from the Admin Console, so handle separately
852 loggingContext.metricStarted();
853 getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine);
854 loggingContext.metricEnded();
855 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
856 } catch (IOException e) {
859 loggingContext.transactionEnded();
860 PolicyLogger.audit("Transaction Ended Successfully");
865 String id = this.getPDPID(request);
866 LOGGER.info("doGet from: " + id);
867 // Get the PDP Object
870 pdp = XACMLPapServlet.papEngine.getPDP(id);
871 } catch (PAPException e) {
876 // Check if request came from localhost
877 if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) {
878 // Return status information - basically all the groups
879 loggingContext.setServiceName("PAP.getGroups");
880 Set<OnapPDPGroup> groups = null;
882 groups = papEngine.getOnapPDPGroups();
883 } catch (PAPException e) {
885 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
886 loggingContext.transactionEnded();
887 PolicyLogger.audit("Transaction Failed - See Error.log");
888 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
892 // convert response object to JSON and include in the response
893 mapperWriteValue(new ObjectMapper(), response, groups);
894 response.setHeader("content-type", "application/json");
895 response.setStatus(HttpServletResponse.SC_OK);
896 loggingContext.transactionEnded();
897 PolicyLogger.audit("Transaction Ended Successfully");
902 "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
903 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
904 loggingContext.transactionEnded();
905 PolicyLogger.audit("Transaction Failed - See Error.log");
906 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
910 loggingContext.setServiceName("PAP.getPolicy");
911 // Get the PDP's Group
912 OnapPDPGroup group = null;
914 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
915 } catch (PAPException e) {
919 String message = "No group associated with pdp " + pdp.getId();
920 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
921 loggingContext.transactionEnded();
922 PolicyLogger.audit("Transaction Failed - See Error.log");
923 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
927 // Which policy do they want?
928 String policyId = request.getParameter("id");
929 if (policyId == null) {
930 String message = "Did not specify an id for the policy";
931 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
932 loggingContext.transactionEnded();
933 PolicyLogger.audit("Transaction Failed - See Error.log");
934 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
938 PDPPolicy policy = group.getPolicy(policyId);
939 if (policy == null) {
940 String message = "Unknown policy: " + policyId;
941 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
942 loggingContext.transactionEnded();
943 PolicyLogger.audit("Transaction Failed - See Error.log");
944 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
949 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : "
950 + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
951 } catch (PAPException | IOException e) {
954 try (InputStream is =
955 new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId);
956 OutputStream os = response.getOutputStream()) {
957 // Send the policy back
958 IOUtils.copy(is, os);
959 response.setStatus(HttpServletResponse.SC_OK);
960 loggingContext.transactionEnded();
961 auditLogger.info("Success");
962 PolicyLogger.audit("Transaction Ended Successfully");
963 } catch (IOException e) {
964 String message = "Failed to open policy id " + policyId;
966 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
967 loggingContext.transactionEnded();
968 PolicyLogger.audit("Transaction Failed - See Error.log");
969 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
971 loggingContext.transactionEnded();
972 PolicyLogger.audit("Transaction Ended");
977 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
980 protected void doPut(HttpServletRequest request, HttpServletResponse response)
981 throws ServletException, IOException {
982 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
983 setLoggingContext(loggingContext, "doPut", "PAP.put");
985 loggingContext.metricStarted();
986 im.startTransaction();
987 loggingContext.metricEnded();
988 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
989 } catch (IntegrityMonitorException e) {
991 "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of "
992 + im.getStateManager().getAdminState() + " and a Standby Status of "
993 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage();
994 LOGGER.info(message, e);
995 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
996 loggingContext.transactionEnded();
997 PolicyLogger.audit("Transaction Failed - See Error.log");
998 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1002 loggingContext.metricStarted();
1003 // need to check if request is from the API or Admin console
1004 String apiflag = request.getParameter("apiflag");
1005 // For Debug purposes
1006 if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) {
1007 XacmlRest.dumpRequest(request);
1008 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1010 loggingContext.metricEnded();
1012 // This would occur if a PolicyDBDao notification was received
1013 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1014 if (policyDBDaoRequestUrl != null) {
1015 LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received.");
1016 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1017 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1018 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1019 if (policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null) {
1020 setResponseError(response, 400, "entityid or entitytype not supplied");
1021 loggingContext.transactionEnded();
1022 PolicyLogger.audit("Transaction Ended Successfully");
1023 im.endTransaction();
1026 loggingContext.metricStarted();
1027 LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1028 HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications();
1029 handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl,
1030 policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this);
1031 loggingContext.metricEnded();
1032 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1033 response.setStatus(200);
1034 loggingContext.transactionEnded();
1035 PolicyLogger.audit("Transaction Ended Successfully");
1036 im.endTransaction();
1040 * Request for ImportService
1042 String importService = request.getParameter("importService");
1043 if (importService != null) {
1044 if (authorizeRequest(request)) {
1045 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1047 loggingContext.metricStarted();
1048 apiRequestHandler.doPut(request, response, importService);
1049 loggingContext.metricEnded();
1050 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1051 } catch (IOException e) {
1054 im.endTransaction();
1058 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1059 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message);
1060 loggingContext.transactionEnded();
1061 PolicyLogger.audit("Transaction Failed - See Error.log");
1062 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1067 // See if this is Admin Console registering itself with us
1069 String acURLString = request.getParameter("adminConsoleURL");
1070 if (acURLString != null) {
1071 loggingContext.setServiceName("AC:PAP.register");
1072 // remember this Admin Console for future updates
1073 if (!adminConsoleURLStringList.contains(acURLString)) {
1074 adminConsoleURLStringList.add(acURLString);
1076 if (LOGGER.isDebugEnabled()) {
1077 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1079 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1080 loggingContext.transactionEnded();
1081 auditLogger.info("Success");
1082 PolicyLogger.audit("Transaction Ended Successfully");
1083 im.endTransaction();
1087 * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step
1088 * process to push policies to the PDP that can now be done From both the Admin Console and
1089 * the PolicyEngine API
1091 String groupId = request.getParameter(GROUPID);
1092 if (groupId != null) {
1093 if (apiflag != null) {
1094 if (!authorizeRequest(request)) {
1096 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1097 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1098 loggingContext.transactionEnded();
1099 PolicyLogger.audit("Transaction Failed - See Error.log");
1100 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1103 if (apiflag.equalsIgnoreCase("addPolicyToGroup")) {
1105 updateGroupsFromAPI(request, response, groupId, loggingContext);
1106 } catch (IOException e) {
1109 loggingContext.transactionEnded();
1110 PolicyLogger.audit("Transaction Ended Successfully");
1111 im.endTransaction();
1115 // this is from the Admin Console, so handle separately
1117 loggingContext.metricEnded();
1118 getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine);
1119 loggingContext.metricEnded();
1120 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1121 } catch (IOException e) {
1124 loggingContext.transactionEnded();
1125 PolicyLogger.audit("Transaction Ended Successfully");
1126 im.endTransaction();
1130 // Request is for policy validation and creation
1132 if (apiflag != null && apiflag.equalsIgnoreCase("admin")) {
1133 // this request is from the Admin Console
1134 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1136 loggingContext.metricStarted();
1137 savePolicyHandler.doPolicyAPIPut(request, response);
1138 loggingContext.metricEnded();
1139 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1140 } catch (IOException e) {
1143 loggingContext.transactionEnded();
1144 PolicyLogger.audit("Transaction Ended Successfully");
1145 im.endTransaction();
1147 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1148 // this request is from the Policy Creation API
1149 if (authorizeRequest(request)) {
1150 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1152 loggingContext.metricStarted();
1153 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1154 loggingContext.metricEnded();
1155 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1156 } catch (IOException e) {
1159 loggingContext.transactionEnded();
1160 PolicyLogger.audit("Transaction Ended Successfully");
1161 im.endTransaction();
1164 String message = "PEP not Authorized for making this Request!!";
1165 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1166 loggingContext.transactionEnded();
1167 PolicyLogger.audit("Transaction Failed - See Error.log");
1168 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1169 im.endTransaction();
1173 // We do not expect anything from anywhere else.
1174 // This method is here in case we ever need to support other operations.
1175 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1176 loggingContext.transactionEnded();
1177 PolicyLogger.audit("Transaction Failed - See Error.log");
1178 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1179 loggingContext.transactionEnded();
1180 PolicyLogger.audit("Transaction Failed - See error.log");
1181 im.endTransaction();
1185 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1188 protected void doDelete(HttpServletRequest request, HttpServletResponse response)
1189 throws ServletException, IOException {
1190 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1191 setLoggingContext(loggingContext, "doDelete", "PAP.delete");
1193 loggingContext.metricStarted();
1194 im.startTransaction();
1195 loggingContext.metricEnded();
1196 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1197 } catch (IntegrityMonitorException ime) {
1199 "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of "
1200 + im.getStateManager().getAdminState() + " and a Standby Status of "
1201 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
1202 LOGGER.info(message, ime);
1203 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1204 loggingContext.transactionEnded();
1205 PolicyLogger.audit("Transaction Failed - See Error.log");
1206 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1209 loggingContext.metricStarted();
1210 XacmlRest.dumpRequest(request);
1211 loggingContext.metricEnded();
1212 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1213 String groupId = request.getParameter(GROUPID);
1214 String apiflag = request.getParameter("apiflag");
1215 if (groupId != null) {
1216 // Is this from the Admin Console or API?
1217 if (apiflag != null) {
1218 if (!authorizeRequest(request)) {
1220 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1221 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1222 loggingContext.transactionEnded();
1223 PolicyLogger.audit("Transaction Failed - See Error.log");
1224 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1227 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1229 loggingContext.metricStarted();
1230 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1231 loggingContext.metricEnded();
1232 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1233 } catch (Exception e) {
1234 LOGGER.error("Exception Occured" + e);
1236 if (apiRequestHandler.getNewGroup() != null) {
1237 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1241 // this is from the Admin Console, so handle separately
1243 loggingContext.metricStarted();
1244 getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine);
1245 loggingContext.metricEnded();
1246 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1247 } catch (IOException e) {
1250 loggingContext.transactionEnded();
1251 PolicyLogger.audit("Transaction Ended Successfully");
1252 im.endTransaction();
1255 // Catch anything that fell through
1256 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1257 loggingContext.transactionEnded();
1258 PolicyLogger.audit("Transaction Failed - See Error.log");
1259 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1260 im.endTransaction();
1263 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1264 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1265 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1266 if (localRootPolicies == null || localReferencedPolicies == null) {
1267 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="
1268 + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies);
1271 // Compare the policies and pipconfig properties to the pdpProperties
1273 // the policy properties includes only xacml.rootPolicies and
1274 // xacml.referencedPolicies without any .url entries
1275 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1276 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1277 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES))
1278 && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES))
1279 && pdpPipConfig.equals(pipconfig)) {
1280 // The PDP is current
1283 } catch (Exception e) {
1284 // we get here if the PDP did not include either xacml.rootPolicies
1285 // or xacml.pip.engines,
1286 // or if there are policies that do not have a corresponding ".url"
1288 // Either of these cases means that the PDP is not up-to-date, so
1289 // just drop-through to return false.
1290 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1295 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1296 String lists[] = new String[2];
1297 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1298 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1299 for (String list : lists) {
1300 if (list != null && list.isEmpty() == false) {
1301 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1302 String url = urlPath + "?id=" + id;
1303 LOGGER.info("Policy URL for " + id + ": " + url);
1304 policies.setProperty(id + ".url", url);
1310 protected String getPDPID(HttpServletRequest request) {
1311 String pdpURL = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID);
1312 if (pdpURL == null || pdpURL.isEmpty()) {
1313 // Should send back its port for identification
1314 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1320 protected String getPDPJMX(HttpServletRequest request) {
1321 String pdpJMMX = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1322 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1323 // Should send back its port for identification
1324 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE
1325 + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1332 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1337 * @param loggingContext
1338 * @throws ServletException
1339 * @throws IOException
1341 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId,
1342 OnapLoggingContext loggingContext) throws IOException {
1343 PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
1344 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1346 String userId = request.getParameter("userId");
1347 // for PUT operations the group may or may not need to exist before
1348 // the operation can be done
1349 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1351 // get the request input stream content into a String
1353 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1354 scanner.useDelimiter("\\A");
1355 json = scanner.hasNext() ? scanner.next() : "";
1358 PolicyLogger.info("pushPolicy request from API: " + json);
1360 // convert Object sent as JSON into local object
1361 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1363 // Get the current policies from the Group and Add the new one
1364 // If the selected policy is in the group we must remove the old
1366 LOGGER.info("Removing old version of the policy");
1367 for (PDPPolicy existingPolicy : group.getPolicies()) {
1368 if (existingPolicy.getName().equals(policy.getName())
1369 && !existingPolicy.getId().equals(policy.getId())) {
1370 group.removePolicy(existingPolicy);
1371 LOGGER.info("Removing policy: " + existingPolicy);
1376 // Assume that this is an update of an existing PDP Group
1377 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1379 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId);
1380 } catch (Exception e) {
1381 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1382 " Error while updating group in the database: " + "group=" + group.getId());
1383 throw new PAPException(e.getMessage());
1386 LOGGER.info("Calling updatGroup() with new group");
1387 papEngine.updateGroup(group);
1388 String policyId = "empty";
1389 if (policy != null && policy.getId() != null) {
1390 policyId = policy.getId();
1392 if (!policyId.matches(REGEX)) {
1393 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1394 response.addHeader("error", ADD_GROUP_ERROR);
1395 response.addHeader("message", "Policy Id is not valid");
1398 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1399 response.addHeader("operation", "push");
1400 response.addHeader("policyId", policyId);
1401 response.addHeader(GROUPID, groupId);
1403 LOGGER.info("Group '" + group.getId() + "' updated");
1405 loggingContext.metricStarted();
1406 acPutTransaction.commitTransaction();
1407 loggingContext.metricEnded();
1408 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1410 // Group changed, which might include changing the policies
1411 groupChanged(group, loggingContext);
1412 loggingContext.transactionEnded();
1413 LOGGER.info("Success");
1416 && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1417 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1418 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1419 LOGGER.debug("Precheck Successful.");
1423 PolicyLogger.audit("Transaction Ended Successfully");
1425 } catch (PAPException e) {
1426 acPutTransaction.rollbackTransaction();
1427 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1428 loggingContext.transactionEnded();
1429 PolicyLogger.audit("Transaction Failed - See Error.log");
1430 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW
1431 + "Exception in request to update group from API - See Error.log on on the PAP.";
1432 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1433 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1434 response.addHeader("error", ADD_GROUP_ERROR);
1435 response.addHeader("message", message);
1441 * HELPER to change Group status when PDP status is changed (Must NOT be called from a method
1442 * that is synchronized on the papEngine or it may deadlock)
1444 public void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
1445 setPDPSummaryStatus(pdp, newStatus.toString());
1448 public void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
1449 synchronized (papEngine) {
1450 StdPDPStatus status = new StdPDPStatus();
1451 status.setStatus(PDPStatus.Status.valueOf(newStatus));
1452 ((StdPDP) pdp).setStatus(status);
1453 // now adjust the group
1454 StdPDPGroup group = (StdPDPGroup) papEngine.getPDPGroup(pdp);
1455 // if the PDP was just deleted it may transiently exist but not be
1457 if (group != null) {
1458 group.resetStatus();
1464 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in
1465 * the PDP group directories
1468 public void changed() {
1469 // all PDPs in all groups need to be updated/sync'd
1470 Set<OnapPDPGroup> groups;
1472 groups = papEngine.getOnapPDPGroups();
1473 } catch (PAPException e) {
1474 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1475 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1477 for (OnapPDPGroup group : groups) {
1478 groupChanged(group);
1482 public void changed(OnapLoggingContext loggingContext) {
1483 // all PDPs in all groups need to be updated/sync'd
1484 Set<OnapPDPGroup> groups;
1486 groups = papEngine.getOnapPDPGroups();
1487 } catch (PAPException e) {
1488 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1489 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1491 for (OnapPDPGroup group : groups) {
1492 groupChanged(group, loggingContext);
1497 public void groupChanged(OnapPDPGroup group) {
1498 // all PDPs within one group need to be updated/sync'd
1499 for (OnapPDP pdp : group.getOnapPdps()) {
1500 pdpChanged(pdp, getPdpDataByGroup(group));
1504 public void groupChanged(OnapPDPGroup group, OnapLoggingContext loggingContext) {
1505 // all PDPs within one group need to be updated/sync'd
1506 for (OnapPDP pdp : group.getOnapPdps()) {
1507 pdpChanged(pdp, loggingContext, getPdpDataByGroup(group));
1512 public void pdpChanged(OnapPDP pdp) {
1513 // kick off a thread to do an event notification for each PDP.
1514 // This needs to be on a separate thread so that PDPs that do not
1515 // respond (down, non-existent, etc)
1516 // do not block the PSP response to the AC, which would freeze the GUI
1517 // until all PDPs sequentially respond or time-out.
1518 Thread t = new Thread(new UpdatePdpThread(pdp, getPdpDataByPdpId(pdp)));
1519 if (CheckPDP.validateID(pdp.getId())) {
1524 public void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext) {
1525 // kick off a thread to do an event notification for each PDP.
1526 // This needs to be on a separate thread so that PDPs that do not
1527 // respond (down, non-existent, etc)
1528 // do not block the PSP response to the AC, which would freeze the GUI
1529 // until all PDPs sequentially respond or time-out.
1530 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, getPdpDataByPdpId(pdp)));
1531 if (CheckPDP.validateID(pdp.getId())) {
1536 private void pdpChanged(OnapPDP pdp, List<Properties> pdpDataByGroup) {
1537 Thread t = new Thread(new UpdatePdpThread(pdp, pdpDataByGroup));
1538 if (CheckPDP.validateID(pdp.getId())) {
1543 private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) {
1544 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup));
1545 if (CheckPDP.validateID(pdp.getId())) {
1550 private List<Properties> getPdpDataByGroup(OnapPDPGroup group) {
1551 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1552 return dataToNotify.setPolicyConfigProperties(group);
1555 private List<Properties> getPdpDataByPdpId(OnapPDP pdp) {
1556 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1557 return dataToNotify.setPolicyConfigProperties(pdp, papEngine);
1560 private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException {
1561 LOGGER.info("Test request received");
1563 im.evaluateSanity();
1564 // If we make it this far, all is well
1565 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
1566 LOGGER.info(message);
1567 loggingContext.transactionEnded();
1568 PolicyLogger.audit("Transaction Failed - See Error.log");
1569 response.setStatus(HttpServletResponse.SC_OK);
1571 } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) {
1573 if (e instanceof ForwardProgressException) {
1574 submsg = " is not making forward progress.";
1575 } else if (e instanceof AdministrativeStateException) {
1576 submsg = " Administrative State is LOCKED.";
1578 submsg = " Standby Status is NOT PROVIDING SERVICE.";
1581 String message = "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: "
1583 LOGGER.info(message, e);
1584 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1585 loggingContext.transactionEnded();
1586 PolicyLogger.audit("Transaction Failed - See Error.log");
1587 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1589 } catch (Exception e) {
1590 // A subsystem is not making progress, is locked, standby or is not
1592 String eMsg = e.getMessage();
1594 eMsg = "No Exception Message";
1596 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
1597 + " Exception Message: " + eMsg;
1598 LOGGER.info(message, e);
1599 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1600 loggingContext.transactionEnded();
1601 PolicyLogger.audit("Transaction Failed - See Error.log");
1602 // Get the specific list of subsystems that failed
1603 String ssFailureList = null;
1604 for (String failedSS : papDependencyGroupsFlatArray) {
1605 if (eMsg.contains(failedSS)) {
1606 if (ssFailureList == null) {
1607 ssFailureList = failedSS;
1609 ssFailureList = ssFailureList.concat("," + failedSS);
1613 if (ssFailureList == null) {
1614 ssFailureList = "UnknownSubSystem";
1616 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
1617 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1622 private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) {
1623 loggingContext.transactionStarted();
1624 loggingContext.setServiceName(serviceName);
1625 if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) {
1626 UUID requestID = UUID.randomUUID();
1627 loggingContext.setRequestId(requestID.toString());
1629 "requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one");
1631 PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
1636 * Authorizing the PEP Requests.
1638 private boolean authorizeRequest(HttpServletRequest request) {
1639 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
1640 // Check if the Client is Authorized.
1641 return clientCredentials != null && clientCredentials.equalsIgnoreCase(environment);
1644 private static void loadWebapps() throws PAPException {
1645 if (actionHome == null || configHome == null) {
1646 Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS));
1648 if (webappsPath == null) {
1649 PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1650 throw new PAPException(
1651 "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1653 Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config");
1654 Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action");
1655 if (Files.notExists(webappsPathConfig)) {
1657 Files.createDirectories(webappsPathConfig);
1658 } catch (IOException e) {
1659 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1660 "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString());
1663 if (Files.notExists(webappsPathAction)) {
1665 Files.createDirectories(webappsPathAction);
1666 } catch (IOException e) {
1667 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
1668 + webappsPathAction.toAbsolutePath().toString(), e);
1671 actionHome = webappsPathAction.toString();
1672 configHome = webappsPathConfig.toString();
1676 public static String getConfigHome() {
1679 } catch (PAPException e) {
1686 private static void setConfigHome() {
1687 configHome = getConfigHome();
1690 public static String getActionHome() {
1693 } catch (PAPException e) {
1700 private static void setActionHome() {
1701 actionHome = getActionHome();
1704 public IntegrityAudit getIa() {
1708 public static String getPDPFile() {
1709 return XACMLPapServlet.pdpFile;
1712 public static String getPersistenceUnit() {
1713 return PERSISTENCE_UNIT;
1716 public static PAPPolicyEngine getPAPEngine() {
1720 public static PolicyDBDaoTransaction getDbDaoTransaction() {
1721 return policyDbDao.getNewTransaction();
1724 public static String getPapDbDriver() {
1728 public static void setPapDbDriver(String papDbDriver) {
1729 XACMLPapServlet.papDbDriver = papDbDriver;
1732 public static String getPapDbUrl() {
1736 public static void setPapDbUrl(String papDbUrl) {
1737 XACMLPapServlet.papDbUrl = papDbUrl;
1740 public static String getPapDbUser() {
1744 public static void setPapDbUser(String papDbUser) {
1745 XACMLPapServlet.papDbUser = papDbUser;
1748 public static String getPapDbPassword() {
1752 public static void setPapDbPassword(String papDbPassword) {
1753 XACMLPapServlet.papDbPd = papDbPassword;
1756 public static String getMsOnapName() {
1760 public static void setMsOnapName(String msOnapName) {
1761 XACMLPapServlet.msOnapName = msOnapName;
1764 public static String getMsPolicyName() {
1765 return msPolicyName;
1768 public static void setMsPolicyName(String msPolicyName) {
1769 XACMLPapServlet.msPolicyName = msPolicyName;
1772 public OnapLoggingContext getBaseLoggingContext() {
1773 return baseLoggingContext;
1776 public void setBaseLoggingContext(OnapLoggingContext baseLoggingContext) {
1777 this.baseLoggingContext = baseLoggingContext;