2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.xacml.rest;
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.api.pap.PDPPolicy;
26 import com.att.research.xacml.api.pap.PDPStatus;
27 import com.att.research.xacml.util.FactoryException;
28 import com.att.research.xacml.util.XACMLProperties;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Splitter;
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.net.InetAddress;
38 import java.net.UnknownHostException;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.util.List;
43 import java.util.Properties;
45 import java.util.UUID;
46 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;
56 import org.apache.commons.io.IOUtils;
57 import org.onap.policy.common.ia.IntegrityAudit;
58 import org.onap.policy.common.im.AdministrativeStateException;
59 import org.onap.policy.common.im.ForwardProgressException;
60 import org.onap.policy.common.im.IntegrityMonitor;
61 import org.onap.policy.common.im.IntegrityMonitorException;
62 import org.onap.policy.common.im.IntegrityMonitorProperties;
63 import org.onap.policy.common.im.StandbyStatusException;
64 import org.onap.policy.common.logging.OnapLoggingContext;
65 import org.onap.policy.common.logging.OnapLoggingUtils;
66 import org.onap.policy.common.logging.eelf.MessageCodes;
67 import org.onap.policy.common.logging.eelf.PolicyLogger;
68 import org.onap.policy.common.logging.flexlogger.FlexLogger;
69 import org.onap.policy.common.logging.flexlogger.Logger;
70 import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications;
71 import org.onap.policy.pap.xacml.rest.components.PolicyDbDao;
72 import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction;
73 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
74 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
75 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
76 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
77 import org.onap.policy.rest.XacmlRest;
78 import org.onap.policy.rest.XacmlRestProperties;
79 import org.onap.policy.rest.dao.PolicyDbException;
80 import org.onap.policy.utils.PeCryptoUtils;
81 import org.onap.policy.utils.PolicyUtils;
82 import org.onap.policy.xacml.api.XACMLErrorConstants;
83 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
84 import org.onap.policy.xacml.api.pap.OnapPDP;
85 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
86 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
87 import org.onap.policy.xacml.std.pap.StdPDP;
88 import org.onap.policy.xacml.std.pap.StdPDPGroup;
89 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
90 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
91 import org.onap.policy.xacml.std.pap.StdPDPStatus;
94 * Servlet implementation class XacmlPapServlet.
97 description = "Implements the XACML PAP RESTful API.",
100 initParams = {@WebInitParam(
101 name = "XACML_PROPERTIES_NAME",
102 value = "xacml.pap.properties",
103 description = "The location of the properties file holding configuration information.")})
104 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
105 private static final long serialVersionUID = 1L;
106 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
107 // audit (transaction) LOGGER
108 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
109 // Persistence Unit for JPA
110 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
111 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
113 private static final String ENVIRONMENT_HEADER = "Environment";
114 private static final String ADD_GROUP_ERROR = "addGroupError";
115 private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
117 private static final String REGEX = "[0-9a-zA-Z._ ]*";
120 * List of Admin Console URLs. Used to send notifications when configuration changes.
122 * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom
123 * changed but often read, so the costs of this approach make sense.
125 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
127 private static String configHome;
128 private static String actionHome;
130 * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET
131 * the Policy files from this process.
133 private static String papUrl = null;
134 // The heartbeat thread.
135 private static Heartbeat heartbeat = null;
136 private static Thread heartbeatThread = null;
137 private static PolicyDbDao policyDbDao;
139 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
141 private static PAPPolicyEngine papEngine = null;
143 * These are the parameters needed for DB access from the PAP
145 private static int papIntegrityAuditPeriodSeconds = -1;
146 private static String papDbDriver = null;
147 private static String papDbUrl = null;
148 private static String papDbUser = null;
149 private static String papDbPd = null;
150 private static String papResourceName = null;
151 private static String[] papDependencyGroupsFlatArray = null;
152 private static String environment = null;
153 private static String pdpFile = null;
155 private transient IntegrityMonitor im;
156 private transient IntegrityAudit ia;
158 // MicroService Model Properties
159 private static String msOnapName;
160 private static String msPolicyName;
162 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
163 * this servlet starts. Its configurable by the admin.
165 private static transient Thread initiateThread = null;
166 private transient OnapLoggingContext baseLoggingContext = null;
167 private static final String GROUPID = "groupId";
170 * @see HttpServlet#HttpServlet()
172 public XACMLPapServlet() {
177 * @see Servlet#init(ServletConfig)
180 public void init(ServletConfig config) throws ServletException {
183 baseLoggingContext = new OnapLoggingContext();
184 // fixed data that will be the same in all logging output goes here
186 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
187 baseLoggingContext.setServer(hostname);
188 } catch (UnknownHostException e) {
189 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
193 XacmlRest.xacmlInit(config);
194 // Load the properties
195 XacmlRest.loadXacmlProperties(null, null);
197 * Retrieve the property values
199 setCommonProperties();
200 String papSiteName = XACMLProperties.getProperty(XacmlRestProperties.PAP_SITE_NAME);
201 if (papSiteName == null) {
202 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
203 " ERROR: Bad papSiteName property entry");
204 throw new PAPException("papSiteName is null");
206 String papNodeType = XACMLProperties.getProperty(XacmlRestProperties.PAP_NODE_TYPE);
207 if (papNodeType == null) {
208 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
209 " ERROR: Bad papNodeType property entry");
210 throw new PAPException("papNodeType is null");
212 // Integer will throw an exception of anything is missing or
214 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
215 int papTransTimeout =
216 Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT));
217 int papAuditTimeout =
218 Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
219 // Boolean will default to false if anything is missing or
221 boolean papAuditFlag =
222 Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
223 boolean papFileSystemAudit =
224 Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_FLAG));
225 String papDependencyGroups = XACMLProperties.getProperty(XacmlRestProperties.PAP_DEPENDENCY_GROUPS);
226 if (papDependencyGroups == null) {
227 throw new PAPException("papDependencyGroups is null");
229 setPAPDependencyGroups(papDependencyGroups);
230 // Integer will throw an exception of anything is missing or
232 int fpMonitorInterval =
233 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
234 int failedCounterThreshold =
235 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
236 int testTransInterval =
237 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
238 int writeFpcInterval =
239 Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
240 LOGGER.debug("\n\n\n**************************************" + "\n*************************************"
241 + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = "
242 + papDbUser + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout
243 + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag
244 + "\n papFileSystemAudit = " + papFileSystemAudit + "\n papResourceName = " + papResourceName
245 + "\n fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = "
246 + failedCounterThreshold + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = "
247 + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + papNodeType
248 + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = "
249 + papIntegrityAuditPeriodSeconds + "\n\n*************************************"
250 + "\n**************************************");
251 // Pull custom persistence settings
252 Properties properties;
254 properties = XACMLProperties.getProperties();
255 LOGGER.debug("\n\n\n**************************************" + "\n**************************************"
256 + "\n\n" + "properties = " + properties + "\n\n**************************************");
257 } catch (IOException e) {
258 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet",
259 " Error loading properties with: " + "XACMLProperties.getProperties()");
260 throw new ServletException(e.getMessage(), e.getCause());
262 // Create an IntegrityMonitor
263 if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
264 properties.setProperty(PERSISTENCE_JDBC_PWD,
265 PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
267 im = IntegrityMonitor.getInstance(papResourceName, properties);
268 // Create an IntegrityAudit
269 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
270 ia.startAuditThread();
271 // we are about to call the PDPs and give them their configuration.
272 // To do that we need to have the URL of this PAP so we can
273 // construct the Policy file URLs
274 setPapUrl(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL));
275 // Create the policyDBDao
277 // Load our PAP engine, first create a factory
278 ONAPPapEngineFactory factory = ONAPPapEngineFactory
279 .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
280 // The factory knows how to go about creating a PAP Engine
281 setPAPEngine(factory.newEngine());
282 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
283 createDefaultGroupOnInit();
285 policyDbDao.setPapEngine(XACMLPapServlet.papEngine);
286 if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
288 * Auditing the local File System groups to be in sync with the Database
291 // get an AuditTransaction to lock out all other transactions
292 PolicyDbDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
294 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
295 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
296 // get the current filesystem group and update from the database
298 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
299 StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group);
300 if (updatedGroup != null) {
301 papEngine.updateGroup(updatedGroup);
303 LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
305 // sync up the config data from DB to file system
306 LOGGER.info("PapServlet: Sync config data from DB to file system");
307 policyDbDao.synchronizeConfigDataInFileSystem();
309 // release the transaction lock
313 // Configurable - have the PAP servlet initiate sending the latest
314 // PDP policy/pip configuration
315 // to all its known PDP nodes.
316 if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
317 startInitiateThreadService(new Thread(this));
319 // After startup, the PAP does Heartbeat's to each of the PDPs
321 startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine));
322 } catch (FactoryException | PAPException e) {
323 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
324 throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e);
325 } catch (Exception e) {
326 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
327 " Failed to create engine - unexpected error");
328 throw new ServletException(
329 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e);
334 private void createDefaultGroupOnInit() {
335 PolicyDbDaoTransaction addNewGroup = null;
337 addNewGroup = policyDbDao.getNewTransaction();
338 OnapPDPGroup group = papEngine.getDefaultGroup();
339 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
340 addNewGroup.commitTransaction();
341 addNewGroup = policyDbDao.getNewTransaction();
342 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
343 addNewGroup.commitTransaction();
344 } catch (Exception e) {
345 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
346 " Error creating new default group in the database");
347 if (addNewGroup != null) {
348 addNewGroup.rollbackTransaction();
353 private static void startInitiateThreadService(Thread thread) {
354 initiateThread = thread;
355 initiateThread.start();
359 protected 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() {
394 protected static void setPAPEngine(PAPPolicyEngine newEngine) {
395 XACMLPapServlet.papEngine = newEngine;
398 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
400 // Now we have flattened the array into a simple comma-separated list
401 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
402 // clean up the entries
403 for (int i = 0; i < papDependencyGroupsFlatArray.length; i++) {
404 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
407 if (XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) {
408 papIntegrityAuditPeriodSeconds = Integer.parseInt(
409 XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
411 } catch (Exception e) {
412 String msg = "integrity_audit_period_seconds ";
413 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
414 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
415 " ERROR: " + msg + "Bad property entry");
418 } catch (Exception e) {
419 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
420 throw new PAPException(e);
424 private static void setCommonProperties() throws PAPException {
427 papDbDriver = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_DRIVER);
428 if (papDbDriver == null) {
429 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
430 " ERROR: Bad papDbDriver property entry");
431 throw new PAPException("papDbDriver is null");
433 setPapDbDriver(papDbDriver);
434 papDbUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_URL);
435 if (papDbUrl == null) {
436 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
437 throw new PAPException("papDbUrl is null");
439 setPapDbUrl(papDbUrl);
440 papDbUser = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_USER);
441 if (papDbUser == null) {
442 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
443 " ERROR: Bad papDbUser property entry");
444 throw new PAPException("papDbUser is null");
446 setPapDbUser(papDbUser);
447 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
448 papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_PASSWORD));
449 if (papDbPd == null) {
450 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
451 " ERROR: Bad papDbPassword property entry");
452 throw new PAPException("papDbPassword is null");
454 setPapDbPassword(papDbPd);
455 papResourceName = XACMLProperties.getProperty(XacmlRestProperties.PAP_RESOURCE_NAME);
456 if (papResourceName == null) {
457 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
458 " ERROR: Bad papResourceName property entry");
459 throw new PAPException("papResourceName is null");
461 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
462 // Micro Service Properties
463 msOnapName = XACMLProperties.getProperty("xacml.policy.msOnapName");
464 setMsOnapName(msOnapName);
465 msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName");
466 setMsPolicyName(msPolicyName);
467 // PDPId File location
468 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
469 if (XACMLPapServlet.pdpFile == null) {
470 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
471 + XacmlRestProperties.PROP_PDP_IDFILE);
472 throw new PAPException(
473 "The PDP Id Authentication File Property :" + XacmlRestProperties.PROP_PDP_IDFILE + " is not Valid. ");
478 * Thread used only during PAP startup to initiate change messages to all known PDPs. This must
479 * be on a separate thread so that any GET requests from the PDPs during this update can be
484 // send the current configuration to all the PDPs that we know about
489 * @see Servlet#destroy()
491 * Depending on how this servlet is run, we may or may not care about cleaning up the
492 * resources. For now we assume that we do care.
495 public void destroy() {
496 // Make sure our threads are destroyed
497 if (XACMLPapServlet.heartbeatThread != null) {
498 // stop the heartbeat
500 if (XACMLPapServlet.heartbeat != null) {
501 XACMLPapServlet.heartbeat.terminate();
503 XACMLPapServlet.heartbeatThread.interrupt();
504 XACMLPapServlet.heartbeatThread.join();
505 } catch (InterruptedException e) {
506 XACMLPapServlet.heartbeatThread.interrupt();
507 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
510 if (initiateThread != null) {
512 initiateThread.interrupt();
513 initiateThread.join();
514 } catch (InterruptedException e) {
515 initiateThread.interrupt();
516 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
523 private ConsoleAndApiService getAcServiceInstance() {
524 return new ConsoleAndApiService();
528 * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make
529 * changes in the PDP Groups.
531 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
534 protected void doPost(HttpServletRequest request, HttpServletResponse response)
535 throws ServletException, IOException {
536 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
537 setLoggingContext(loggingContext, "doPost", "PAP.post");
538 PolicyDbDaoTransaction pdpTransaction = null;
540 loggingContext.metricStarted();
541 im.startTransaction();
542 loggingContext.metricEnded();
543 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
544 } catch (AdministrativeStateException ae) {
546 "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
547 + im.getStateManager().getAdminState() + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
548 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
549 loggingContext.metricEnded();
550 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
551 loggingContext.transactionEnded();
552 PolicyLogger.audit("Transaction Failed - See Error.log");
553 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
555 } catch (IntegrityMonitorException ime) {
557 "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
558 + im.getStateManager().getAdminState() + " and a Standby Status of "
559 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
560 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime);
561 loggingContext.metricEnded();
562 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
563 loggingContext.transactionEnded();
564 PolicyLogger.audit("Transaction Failed - See Error.log");
565 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
569 loggingContext.metricStarted();
570 XacmlRest.dumpRequest(request);
571 loggingContext.metricEnded();
572 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
573 // since getParameter reads the content string, explicitly get the
574 // content before doing that.
575 // Simply getting the inputStream seems to protect it against being
576 // consumed by getParameter.
577 request.getInputStream();
578 String groupId = request.getParameter(GROUPID);
579 String apiflag = request.getParameter("apiflag");
580 if (groupId != null) {
581 // Is this from the Admin Console or API?
582 if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
583 // this is from the API so we need to check the client
584 // credentials before processing the request
585 if (!authorizeRequest(request)) {
586 String message = "PEP not Authorized for making this Request!!";
587 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
588 loggingContext.transactionEnded();
589 PolicyLogger.audit("Transaction Failed - See Error.log");
590 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
595 loggingContext.metricStarted();
596 getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine);
597 loggingContext.metricEnded();
598 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
599 loggingContext.transactionEnded();
600 PolicyLogger.audit("Transaction Ended Successfully");
604 // Request is from a PDP asking for its config.
605 loggingContext.setServiceName("PDP:PAP.register");
607 String id = this.getPDPID(request);
608 String jmxport = this.getPDPJMX(request);
609 LOGGER.info("Request(doPost) from PDP coming up: " + id);
610 // Get the PDP Object
611 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
614 LOGGER.info("Unknown PDP: " + id);
616 if (CheckPDP.validateID(id)) {
617 pdpTransaction = policyDbDao.getNewTransaction();
619 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id,
620 "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
621 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id,
622 "Registered on first startup", Integer.parseInt(jmxport));
623 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException
624 | PersistenceException | PolicyDbException e) {
625 pdpTransaction.rollbackTransaction();
626 String message = "Failed to create new PDP for id: " + id;
627 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
628 loggingContext.transactionEnded();
629 PolicyLogger.audit("Transaction Failed - See Error.log");
630 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
634 // get the PDP we just created
636 pdp = XACMLPapServlet.papEngine.getPDP(id);
637 } catch (PAPException e) {
641 if (pdpTransaction != null) {
642 pdpTransaction.rollbackTransaction();
644 String message = "Failed to create new PDP for id: " + id;
645 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
646 loggingContext.transactionEnded();
647 PolicyLogger.audit("Transaction Failed - See Error.log");
648 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
653 String message = "PDP is Unauthorized to Connect to PAP: " + id;
654 loggingContext.transactionEnded();
655 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
656 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
657 "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
658 PolicyLogger.audit("Transaction Failed - See Error.log");
663 loggingContext.metricStarted();
664 pdpTransaction.commitTransaction();
665 loggingContext.metricEnded();
666 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
667 } catch (Exception e) {
668 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
669 "Could not commit transaction to put pdp in the database");
672 if (jmxport != null && !"".equals(jmxport)) {
674 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
675 } catch (NumberFormatException e) {
679 // Get the PDP's Group
680 OnapPDPGroup group = null;
682 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
683 } catch (PAPException e) {
688 .error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
689 loggingContext.transactionEnded();
690 PolicyLogger.audit("Transaction Failed - See Error.log");
691 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
692 "PDP not associated with any group, even the default");
696 // Determine what group the PDP node is in and get
697 // its policy/pip properties.
698 Properties policies = group.getPolicyProperties();
699 Properties pipconfig = group.getPipConfigProperties();
700 // Get the current policy/pip configuration that the PDP has
701 Properties pdpProperties = new Properties();
703 pdpProperties.load(request.getInputStream());
704 } catch (IOException e) {
707 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
708 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
709 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
710 // Validate the node's properties
711 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
712 // Send back current configuration
714 // Tell the PDP we are sending back the current policies/pip
716 LOGGER.info("PDP configuration NOT current.");
717 if (policies != null) {
718 // Put URL's into the properties in case the PDP needs to
720 this.populatePolicyURL(request.getRequestURL(), policies);
721 // Copy the properties to the output stream
723 policies.store(response.getOutputStream(), "");
724 } catch (IOException e) {
728 if (pipconfig != null) {
729 // Copy the properties to the output stream
731 pipconfig.store(response.getOutputStream(), "");
732 } catch (IOException e) {
736 // We are good - and we are sending them information
737 response.setStatus(HttpServletResponse.SC_OK);
739 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
740 } catch (PAPException e) {
744 // Tell them they are good
745 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
747 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
748 } catch (PAPException e) {
752 auditLogger.info("Success");
753 PolicyLogger.audit("Transaction Ended Successfully");
754 } catch (PAPException | IOException | NumberFormatException e) {
755 if (pdpTransaction != null) {
756 pdpTransaction.rollbackTransaction();
758 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
759 loggingContext.transactionEnded();
760 PolicyLogger.audit("Transaction Failed - See Error.log");
761 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
765 // Catch anything that fell through
766 loggingContext.transactionEnded();
767 PolicyLogger.audit("Transaction Ended");
771 private void setResponseError(HttpServletResponse response, int responseCode, String message) {
773 if (message != null && !message.isEmpty()) {
774 response.sendError(responseCode, message);
776 } catch (IOException e) {
777 LOGGER.error("Error setting Error response Header ", e);
782 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
785 protected void doGet(HttpServletRequest request, HttpServletResponse response)
786 throws ServletException, IOException {
787 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
788 setLoggingContext(loggingContext, "doGet", "PAP.get");
789 loggingContext.metricStarted();
790 XacmlRest.dumpRequest(request);
791 loggingContext.metricEnded();
792 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
793 String pathInfo = request.getRequestURI();
794 LOGGER.info("path info: " + pathInfo);
795 if (pathInfo != null && "/pap/test".equals(pathInfo)) {
796 // DO NOT do a im.startTransaction for the test request
798 testService(loggingContext, response);
799 } catch (IOException e) {
804 // This im.startTransaction() covers all other Get transactions
806 loggingContext.metricStarted();
807 im.startTransaction();
808 loggingContext.metricEnded();
809 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
810 } catch (IntegrityMonitorException ime) {
812 "GET interface called for PAP " + papResourceName + " but it has an Administrative state of "
813 + im.getStateManager().getAdminState() + " and a Standby Status of "
814 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
815 LOGGER.info(message, ime);
816 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
817 loggingContext.transactionEnded();
818 PolicyLogger.audit("Transaction Failed - See Error.log");
819 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
822 // Request from the API to get the gitPath
823 String apiflag = request.getParameter("apiflag");
824 if (apiflag != null) {
825 if (authorizeRequest(request)) {
826 APIRequestHandler apiRequestHandler = new APIRequestHandler();
828 loggingContext.metricStarted();
829 apiRequestHandler.doGet(request, response, apiflag);
830 loggingContext.metricEnded();
831 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
832 } catch (IOException e) {
835 loggingContext.transactionEnded();
836 PolicyLogger.audit("Transaction Ended Successfully");
841 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
842 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
843 loggingContext.transactionEnded();
844 PolicyLogger.audit("Transaction Failed - See Error.log");
845 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
850 // Is this from the Admin Console?
851 String groupId = request.getParameter(GROUPID);
852 if (groupId != null) {
853 // this is from the Admin Console, so handle separately
855 loggingContext.metricStarted();
856 getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine);
857 loggingContext.metricEnded();
858 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
859 } catch (IOException e) {
862 loggingContext.transactionEnded();
863 PolicyLogger.audit("Transaction Ended Successfully");
868 String id = this.getPDPID(request);
869 LOGGER.info("doGet from: " + id);
870 // Get the PDP Object
873 pdp = XACMLPapServlet.papEngine.getPDP(id);
874 } catch (PAPException e) {
879 // Check if request came from localhost
880 if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) {
881 // Return status information - basically all the groups
882 loggingContext.setServiceName("PAP.getGroups");
883 Set<OnapPDPGroup> groups = null;
885 groups = papEngine.getOnapPDPGroups();
886 } catch (PAPException e) {
888 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
889 loggingContext.transactionEnded();
890 PolicyLogger.audit("Transaction Failed - See Error.log");
891 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
895 // convert response object to JSON and include in the response
896 mapperWriteValue(new ObjectMapper(), response, groups);
897 response.setHeader("content-type", "application/json");
898 response.setStatus(HttpServletResponse.SC_OK);
899 loggingContext.transactionEnded();
900 PolicyLogger.audit("Transaction Ended Successfully");
905 "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
906 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
907 loggingContext.transactionEnded();
908 PolicyLogger.audit("Transaction Failed - See Error.log");
909 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
913 loggingContext.setServiceName("PAP.getPolicy");
914 // Get the PDP's Group
915 OnapPDPGroup group = null;
917 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
918 } catch (PAPException e) {
922 String message = "No group associated with pdp " + pdp.getId();
923 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
924 loggingContext.transactionEnded();
925 PolicyLogger.audit("Transaction Failed - See Error.log");
926 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
930 // Which policy do they want?
931 String policyId = request.getParameter("id");
932 if (policyId == null) {
933 String message = "Did not specify an id for the policy";
934 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
935 loggingContext.transactionEnded();
936 PolicyLogger.audit("Transaction Failed - See Error.log");
937 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
941 PDPPolicy policy = group.getPolicy(policyId);
942 if (policy == null) {
943 String message = "Unknown policy: " + policyId;
944 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
945 loggingContext.transactionEnded();
946 PolicyLogger.audit("Transaction Failed - See Error.log");
947 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
952 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : "
953 + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
954 } catch (PAPException | IOException e) {
959 new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId);
960 OutputStream os = response.getOutputStream()) {
961 // Send the policy back
962 IOUtils.copy(is, os);
963 response.setStatus(HttpServletResponse.SC_OK);
964 loggingContext.transactionEnded();
965 auditLogger.info("Success");
966 PolicyLogger.audit("Transaction Ended Successfully");
967 } catch (IOException e) {
968 String message = "Failed to open policy id " + policyId;
970 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
971 loggingContext.transactionEnded();
972 PolicyLogger.audit("Transaction Failed - See Error.log");
973 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
975 loggingContext.transactionEnded();
976 PolicyLogger.audit("Transaction Ended");
981 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
984 protected void doPut(HttpServletRequest request, HttpServletResponse response)
985 throws ServletException, IOException {
986 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
987 setLoggingContext(loggingContext, "doPut", "PAP.put");
989 loggingContext.metricStarted();
990 im.startTransaction();
991 loggingContext.metricEnded();
992 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
993 } catch (IntegrityMonitorException e) {
995 "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of "
996 + im.getStateManager().getAdminState() + " and a Standby Status of "
997 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage();
998 LOGGER.info(message, e);
999 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1000 loggingContext.transactionEnded();
1001 PolicyLogger.audit("Transaction Failed - See Error.log");
1002 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1006 loggingContext.metricStarted();
1007 // need to check if request is from the API or Admin console
1008 String apiflag = request.getParameter("apiflag");
1009 // For Debug purposes
1010 if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) {
1011 XacmlRest.dumpRequest(request);
1012 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1014 loggingContext.metricEnded();
1016 // This would occur if a PolicyDBDao notification was received
1017 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1018 if (policyDBDaoRequestUrl != null) {
1019 LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received.");
1020 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1021 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1022 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1023 if (policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null) {
1024 setResponseError(response, 400, "entityid or entitytype not supplied");
1025 loggingContext.transactionEnded();
1026 PolicyLogger.audit("Transaction Ended Successfully");
1027 im.endTransaction();
1030 loggingContext.metricStarted();
1031 LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1032 HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications();
1033 handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl,
1034 policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this);
1035 loggingContext.metricEnded();
1036 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1037 response.setStatus(200);
1038 loggingContext.transactionEnded();
1039 PolicyLogger.audit("Transaction Ended Successfully");
1040 im.endTransaction();
1044 * Request for ImportService
1046 String importService = request.getParameter("importService");
1047 if (importService != null) {
1048 if (authorizeRequest(request)) {
1049 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1051 loggingContext.metricStarted();
1052 apiRequestHandler.doPut(request, response, importService);
1053 loggingContext.metricEnded();
1054 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1055 } catch (IOException e) {
1058 im.endTransaction();
1062 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1063 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message);
1064 loggingContext.transactionEnded();
1065 PolicyLogger.audit("Transaction Failed - See Error.log");
1066 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1071 // See if this is Admin Console registering itself with us
1073 String acURLString = request.getParameter("adminConsoleURL");
1074 if (acURLString != null) {
1075 loggingContext.setServiceName("AC:PAP.register");
1076 // remember this Admin Console for future updates
1077 if (!adminConsoleURLStringList.contains(acURLString)) {
1078 adminConsoleURLStringList.add(acURLString);
1080 if (LOGGER.isDebugEnabled()) {
1081 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1083 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1084 loggingContext.transactionEnded();
1085 auditLogger.info("Success");
1086 PolicyLogger.audit("Transaction Ended Successfully");
1087 im.endTransaction();
1091 * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step
1092 * process to push policies to the PDP that can now be done From both the Admin Console and
1093 * the PolicyEngine API
1095 String groupId = request.getParameter(GROUPID);
1096 if (groupId != null) {
1097 if (apiflag != null) {
1098 if (!authorizeRequest(request)) {
1100 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1101 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1102 loggingContext.transactionEnded();
1103 PolicyLogger.audit("Transaction Failed - See Error.log");
1104 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1107 if (apiflag.equalsIgnoreCase("addPolicyToGroup")) {
1109 updateGroupsFromAPI(request, response, groupId, loggingContext);
1110 } catch (IOException e) {
1113 loggingContext.transactionEnded();
1114 PolicyLogger.audit("Transaction Ended Successfully");
1115 im.endTransaction();
1119 // this is from the Admin Console, so handle separately
1121 loggingContext.metricEnded();
1122 getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine);
1123 loggingContext.metricEnded();
1124 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1125 } catch (IOException e) {
1128 loggingContext.transactionEnded();
1129 PolicyLogger.audit("Transaction Ended Successfully");
1130 im.endTransaction();
1134 // Request is for policy validation and creation
1136 if (apiflag != null && apiflag.equalsIgnoreCase("admin")) {
1137 // this request is from the Admin Console
1138 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1140 loggingContext.metricStarted();
1141 savePolicyHandler.doPolicyAPIPut(request, response);
1142 loggingContext.metricEnded();
1143 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1144 } catch (IOException e) {
1147 loggingContext.transactionEnded();
1148 PolicyLogger.audit("Transaction Ended Successfully");
1149 im.endTransaction();
1151 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1152 // this request is from the Policy Creation API
1153 if (authorizeRequest(request)) {
1154 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1156 loggingContext.metricStarted();
1157 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1158 loggingContext.metricEnded();
1159 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1160 } catch (IOException e) {
1163 loggingContext.transactionEnded();
1164 PolicyLogger.audit("Transaction Ended Successfully");
1165 im.endTransaction();
1168 String message = "PEP not Authorized for making this Request!!";
1169 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1170 loggingContext.transactionEnded();
1171 PolicyLogger.audit("Transaction Failed - See Error.log");
1172 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1173 im.endTransaction();
1177 // We do not expect anything from anywhere else.
1178 // This method is here in case we ever need to support other operations.
1179 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1180 loggingContext.transactionEnded();
1181 PolicyLogger.audit("Transaction Failed - See Error.log");
1182 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1183 loggingContext.transactionEnded();
1184 PolicyLogger.audit("Transaction Failed - See error.log");
1185 im.endTransaction();
1189 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1192 protected void doDelete(HttpServletRequest request, HttpServletResponse response)
1193 throws ServletException, IOException {
1194 OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1195 setLoggingContext(loggingContext, "doDelete", "PAP.delete");
1197 loggingContext.metricStarted();
1198 im.startTransaction();
1199 loggingContext.metricEnded();
1200 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1201 } catch (IntegrityMonitorException ime) {
1203 "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of "
1204 + im.getStateManager().getAdminState() + " and a Standby Status of "
1205 + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
1206 LOGGER.info(message, ime);
1207 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1208 loggingContext.transactionEnded();
1209 PolicyLogger.audit("Transaction Failed - See Error.log");
1210 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1213 loggingContext.metricStarted();
1214 XacmlRest.dumpRequest(request);
1215 loggingContext.metricEnded();
1216 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1217 String groupId = request.getParameter(GROUPID);
1218 String apiflag = request.getParameter("apiflag");
1219 if (groupId != null) {
1220 // Is this from the Admin Console or API?
1221 if (apiflag != null) {
1222 if (!authorizeRequest(request)) {
1224 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1225 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1226 loggingContext.transactionEnded();
1227 PolicyLogger.audit("Transaction Failed - See Error.log");
1228 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1231 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1233 loggingContext.metricStarted();
1234 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1235 loggingContext.metricEnded();
1236 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1237 } catch (Exception e) {
1238 LOGGER.error("Exception Occured" + e);
1240 if (apiRequestHandler.getNewGroup() != null) {
1241 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1245 // this is from the Admin Console, so handle separately
1247 loggingContext.metricStarted();
1248 getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine);
1249 loggingContext.metricEnded();
1250 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1251 } catch (IOException e) {
1254 loggingContext.transactionEnded();
1255 PolicyLogger.audit("Transaction Ended Successfully");
1256 im.endTransaction();
1259 // Catch anything that fell through
1260 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1261 loggingContext.transactionEnded();
1262 PolicyLogger.audit("Transaction Failed - See Error.log");
1263 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1264 im.endTransaction();
1267 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1268 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1269 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1270 if (localRootPolicies == null || localReferencedPolicies == null) {
1271 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="
1272 + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies);
1275 // Compare the policies and pipconfig properties to the pdpProperties
1277 // the policy properties includes only xacml.rootPolicies and
1278 // xacml.referencedPolicies without any .url entries
1279 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1280 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1281 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES))
1282 && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES))
1283 && pdpPipConfig.equals(pipconfig)) {
1284 // The PDP is current
1287 } catch (Exception e) {
1288 // we get here if the PDP did not include either xacml.rootPolicies
1289 // or xacml.pip.engines,
1290 // or if there are policies that do not have a corresponding ".url"
1292 // Either of these cases means that the PDP is not up-to-date, so
1293 // just drop-through to return false.
1294 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1300 protected void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1301 String lists[] = new String[2];
1302 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1303 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1304 for (String list : lists) {
1305 if (list != null && list.isEmpty() == false) {
1306 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1307 String url = urlPath + "?id=" + id;
1308 LOGGER.info("Policy URL for " + id + ": " + url);
1309 policies.setProperty(id + ".url", url);
1315 protected String getPDPID(HttpServletRequest request) {
1316 String pdpURL = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID);
1317 if (pdpURL == null || pdpURL.isEmpty()) {
1318 // Should send back its port for identification
1319 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1325 protected String getPDPJMX(HttpServletRequest request) {
1326 String pdpJMMX = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1327 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1328 // Should send back its port for identification
1329 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE
1330 + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1337 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1342 * @param loggingContext
1343 * @throws ServletException
1344 * @throws IOException
1346 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId,
1347 OnapLoggingContext loggingContext) throws IOException {
1348 PolicyDbDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
1349 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1351 String userId = request.getParameter("userId");
1352 // for PUT operations the group may or may not need to exist before
1353 // the operation can be done
1354 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1356 // get the request input stream content into a String
1358 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1359 scanner.useDelimiter("\\A");
1360 json = scanner.hasNext() ? scanner.next() : "";
1363 PolicyLogger.info("pushPolicy request from API: " + json);
1365 // convert Object sent as JSON into local object
1366 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1368 // Get the current policies from the Group and Add the new one
1369 // If the selected policy is in the group we must remove the old
1371 LOGGER.info("Removing old version of the policy");
1372 for (PDPPolicy existingPolicy : group.getPolicies()) {
1373 if (existingPolicy.getName().equals(policy.getName())
1374 && !existingPolicy.getId().equals(policy.getId())) {
1375 group.removePolicy(existingPolicy);
1376 LOGGER.info("Removing policy: " + existingPolicy);
1381 // Assume that this is an update of an existing PDP Group
1382 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1384 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId);
1385 } catch (Exception e) {
1386 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1387 " Error while updating group in the database: " + "group=" + group.getId());
1388 throw new PAPException(e.getMessage());
1391 LOGGER.info("Calling updatGroup() with new group");
1392 papEngine.updateGroup(group);
1393 String policyId = "empty";
1394 if (policy != null && policy.getId() != null) {
1395 policyId = policy.getId();
1397 if (!policyId.matches(REGEX)) {
1398 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1399 response.addHeader("error", ADD_GROUP_ERROR);
1400 response.addHeader("message", "Policy Id is not valid");
1403 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1404 response.addHeader("operation", "push");
1405 response.addHeader("policyId", policyId);
1406 response.addHeader(GROUPID, groupId);
1408 LOGGER.info("Group '" + group.getId() + "' updated");
1410 loggingContext.metricStarted();
1411 acPutTransaction.commitTransaction();
1412 loggingContext.metricEnded();
1413 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1415 // Group changed, which might include changing the policies
1416 groupChanged(group, loggingContext);
1417 loggingContext.transactionEnded();
1418 LOGGER.info("Success");
1421 && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1422 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1423 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1424 LOGGER.debug("Precheck Successful.");
1428 PolicyLogger.audit("Transaction Ended Successfully");
1430 } catch (PAPException e) {
1431 acPutTransaction.rollbackTransaction();
1432 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1433 loggingContext.transactionEnded();
1434 PolicyLogger.audit("Transaction Failed - See Error.log");
1435 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW
1436 + "Exception in request to update group from API - See Error.log on on the PAP.";
1437 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1438 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1439 response.addHeader("error", ADD_GROUP_ERROR);
1440 response.addHeader("message", message);
1446 * HELPER to change Group status when PDP status is changed (Must NOT be called from a method
1447 * that is synchronized on the papEngine or it may deadlock)
1449 public void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
1450 setPDPSummaryStatus(pdp, newStatus.toString());
1453 public void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
1454 synchronized (papEngine) {
1455 StdPDPStatus status = new StdPDPStatus();
1456 status.setStatus(PDPStatus.Status.valueOf(newStatus));
1457 ((StdPDP) pdp).setStatus(status);
1458 // now adjust the group
1459 StdPDPGroup group = (StdPDPGroup) papEngine.getPDPGroup(pdp);
1460 // if the PDP was just deleted it may transiently exist but not be
1462 if (group != null) {
1463 group.resetStatus();
1469 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in
1470 * the PDP group directories
1473 public void changed() {
1474 // all PDPs in all groups need to be updated/sync'd
1475 Set<OnapPDPGroup> groups;
1477 groups = papEngine.getOnapPDPGroups();
1478 } catch (PAPException e) {
1479 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1480 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1482 for (OnapPDPGroup group : groups) {
1483 groupChanged(group);
1487 public void changed(OnapLoggingContext loggingContext) {
1488 // all PDPs in all groups need to be updated/sync'd
1489 Set<OnapPDPGroup> groups;
1491 groups = papEngine.getOnapPDPGroups();
1492 } catch (PAPException e) {
1493 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1494 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1496 for (OnapPDPGroup group : groups) {
1497 groupChanged(group, loggingContext);
1502 public void groupChanged(OnapPDPGroup group) {
1503 // all PDPs within one group need to be updated/sync'd
1504 for (OnapPDP pdp : group.getOnapPdps()) {
1505 pdpChanged(pdp, getPdpDataByGroup(group));
1509 public void groupChanged(OnapPDPGroup group, OnapLoggingContext loggingContext) {
1510 // all PDPs within one group need to be updated/sync'd
1511 for (OnapPDP pdp : group.getOnapPdps()) {
1512 pdpChanged(pdp, loggingContext, getPdpDataByGroup(group));
1517 public void pdpChanged(OnapPDP pdp) {
1518 // kick off a thread to do an event notification for each PDP.
1519 // This needs to be on a separate thread so that PDPs that do not
1520 // respond (down, non-existent, etc)
1521 // do not block the PSP response to the AC, which would freeze the GUI
1522 // until all PDPs sequentially respond or time-out.
1523 Thread t = new Thread(new UpdatePdpThread(pdp, getPdpDataByPdpId(pdp)));
1524 if (CheckPDP.validateID(pdp.getId())) {
1529 public void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext) {
1530 // kick off a thread to do an event notification for each PDP.
1531 // This needs to be on a separate thread so that PDPs that do not
1532 // respond (down, non-existent, etc)
1533 // do not block the PSP response to the AC, which would freeze the GUI
1534 // until all PDPs sequentially respond or time-out.
1535 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, getPdpDataByPdpId(pdp)));
1536 if (CheckPDP.validateID(pdp.getId())) {
1541 private void pdpChanged(OnapPDP pdp, List<Properties> pdpDataByGroup) {
1542 Thread t = new Thread(new UpdatePdpThread(pdp, pdpDataByGroup));
1543 if (CheckPDP.validateID(pdp.getId())) {
1548 private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) {
1549 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup));
1550 if (CheckPDP.validateID(pdp.getId())) {
1555 private List<Properties> getPdpDataByGroup(OnapPDPGroup group) {
1556 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1557 return dataToNotify.setPolicyConfigProperties(group);
1560 private List<Properties> getPdpDataByPdpId(OnapPDP pdp) {
1561 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1562 return dataToNotify.setPolicyConfigProperties(pdp, papEngine);
1565 private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException {
1566 LOGGER.info("Test request received");
1568 im.evaluateSanity();
1569 // If we make it this far, all is well
1570 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
1571 LOGGER.info(message);
1572 loggingContext.transactionEnded();
1573 PolicyLogger.audit("Transaction Failed - See Error.log");
1574 response.setStatus(HttpServletResponse.SC_OK);
1576 } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) {
1578 if (e instanceof ForwardProgressException) {
1579 submsg = " is not making forward progress.";
1580 } else if (e instanceof AdministrativeStateException) {
1581 submsg = " Administrative State is LOCKED.";
1583 submsg = " Standby Status is NOT PROVIDING SERVICE.";
1587 "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: " + e.getMessage();
1588 LOGGER.info(message, e);
1589 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1590 loggingContext.transactionEnded();
1591 PolicyLogger.audit("Transaction Failed - See Error.log");
1592 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1594 } catch (Exception e) {
1595 // A subsystem is not making progress, is locked, standby or is not
1597 String eMsg = e.getMessage();
1599 eMsg = "No Exception Message";
1601 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
1602 + " Exception Message: " + eMsg;
1603 LOGGER.info(message, e);
1604 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1605 loggingContext.transactionEnded();
1606 PolicyLogger.audit("Transaction Failed - See Error.log");
1607 // Get the specific list of subsystems that failed
1608 String ssFailureList = null;
1609 for (String failedSS : papDependencyGroupsFlatArray) {
1610 if (eMsg.contains(failedSS)) {
1611 if (ssFailureList == null) {
1612 ssFailureList = failedSS;
1614 ssFailureList = ssFailureList.concat("," + failedSS);
1618 if (ssFailureList == null) {
1619 ssFailureList = "UnknownSubSystem";
1621 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
1622 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1627 private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) {
1628 loggingContext.transactionStarted();
1629 loggingContext.setServiceName(serviceName);
1630 if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) {
1631 UUID requestID = UUID.randomUUID();
1632 loggingContext.setRequestId(requestID.toString());
1634 .info("requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one");
1636 PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
1641 * Authorizing the PEP Requests.
1643 private boolean authorizeRequest(HttpServletRequest request) {
1644 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
1645 // Check if the Client is Authorized.
1646 return clientCredentials != null && clientCredentials.equalsIgnoreCase(environment);
1649 private static void loadWebapps() throws PAPException {
1650 if (actionHome == null || configHome == null) {
1651 Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS));
1653 if (webappsPath == null) {
1654 PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1655 throw new PAPException(
1656 "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1658 Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config");
1659 Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action");
1660 if (Files.notExists(webappsPathConfig)) {
1662 Files.createDirectories(webappsPathConfig);
1663 } catch (IOException e) {
1664 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1665 "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString());
1668 if (Files.notExists(webappsPathAction)) {
1670 Files.createDirectories(webappsPathAction);
1671 } catch (IOException e) {
1672 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
1673 + webappsPathAction.toAbsolutePath().toString(), e);
1676 actionHome = webappsPathAction.toString();
1677 configHome = webappsPathConfig.toString();
1681 public static String getConfigHome() {
1684 } catch (PAPException e) {
1691 private static void setConfigHome() {
1692 configHome = getConfigHome();
1695 public static String getActionHome() {
1698 } catch (PAPException e) {
1705 private static void setActionHome() {
1706 actionHome = getActionHome();
1709 public IntegrityAudit getIa() {
1713 public static String getPDPFile() {
1714 return XACMLPapServlet.pdpFile;
1717 public static String getPersistenceUnit() {
1718 return PERSISTENCE_UNIT;
1721 public static PAPPolicyEngine getPAPEngine() {
1725 public static PolicyDbDaoTransaction getDbDaoTransaction() {
1726 return policyDbDao.getNewTransaction();
1729 public static String getPapDbDriver() {
1733 public static void setPapDbDriver(String papDbDriver) {
1734 XACMLPapServlet.papDbDriver = papDbDriver;
1737 public static String getPapDbUrl() {
1741 public static void setPapDbUrl(String papDbUrl) {
1742 XACMLPapServlet.papDbUrl = papDbUrl;
1745 public static String getPapDbUser() {
1749 public static void setPapDbUser(String papDbUser) {
1750 XACMLPapServlet.papDbUser = papDbUser;
1753 public static String getPapDbPassword() {
1757 public static void setPapDbPassword(String papDbPassword) {
1758 XACMLPapServlet.papDbPd = papDbPassword;
1761 public static String getMsOnapName() {
1765 public static void setMsOnapName(String msOnapName) {
1766 XACMLPapServlet.msOnapName = msOnapName;
1769 public static String getMsPolicyName() {
1770 return msPolicyName;
1773 public static void setMsPolicyName(String msPolicyName) {
1774 XACMLPapServlet.msPolicyName = msPolicyName;
1777 public OnapLoggingContext getBaseLoggingContext() {
1778 return baseLoggingContext;
1781 public void setBaseLoggingContext(OnapLoggingContext baseLoggingContext) {
1782 this.baseLoggingContext = baseLoggingContext;