6bef28dfb27cc7f3af10aa68af7d1d52b88b0226
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / XACMLRest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.rest;
22
23 import java.io.IOException;
24 import java.util.Enumeration;
25 import java.util.Map;
26 import java.util.Properties;
27 import java.util.Set;
28
29 import javax.servlet.ServletConfig;
30 import javax.servlet.http.HttpServletRequest;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.onap.policy.common.logging.eelf.MessageCodes;
35 import org.onap.policy.common.logging.eelf.PolicyLogger;
36
37 import com.att.research.xacml.util.XACMLProperties;
38
39
40 /**
41  * This static class is used by both the PDP and PAP servlet's. It contains some common
42  * static functions and objects used by both the servlet's.
43  * 
44  *
45  */
46 public class XACMLRest {
47         private static final Log logger = LogFactory.getLog(XACMLRest.class);
48         private static Properties restProperties = new Properties();
49         
50         /**
51          * This must be called during servlet initialization. It sets up the xacml.?.properties
52          * file as a system property. If the System property is already set, then it does not
53          * do anything. This allows the developer to specify their own xacml.properties file to be
54          * used. They can 1) modify the default properties that comes with the project, or 2) change
55          * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set
56          * the Java System property to point to their xacml.properties file.
57          * 
58          * The recommended way of overriding the default xacml.properties file is using a Java System
59          * property:
60          * 
61          * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties
62          * 
63          * This way one does not change any actual code or files in the project and can leave the 
64          * defaults alone.
65          * 
66          * @param config - The servlet config file passed from the javax servlet init() function
67          */
68         public static void xacmlInit(ServletConfig config) {
69                 //
70                 // Get the XACML Properties File parameter first
71                 //
72                 String propFile = config.getInitParameter("XACML_PROPERTIES_NAME");
73                 if (propFile != null) {
74                         //
75                         // Look for system override
76                         //
77                         String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME);
78                         logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME);
79                         if (xacmlPropertiesName == null) {
80                                 //
81                                 // Set it to our servlet default
82                                 //
83                                 if (logger.isDebugEnabled()) {
84                                         logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile);
85                                 }
86                                 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile);
87                         } else {
88                                 if (logger.isDebugEnabled()) {
89                                         logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName);
90                                 }
91                         }
92                 }
93                 //
94                 // Setup the remaining properties
95                 //
96                 Enumeration<String> params = config.getInitParameterNames();
97                 while (params.hasMoreElements()) {
98                         String param = params.nextElement();
99                         if (! param.equals("XACML_PROPERTIES_NAME")) {
100                                 String value = config.getInitParameter(param);
101                                 //logger.info(param + "=" + config.getInitParameter(param));
102                                 PolicyLogger.info(param + "=" + config.getInitParameter(param));
103                                 restProperties.setProperty(param, value);
104                         }
105                 }
106         }
107         
108         /**
109          * Reset's the XACMLProperties internal properties object so we start
110          * in a fresh environment. Then adds back in our Servlet init properties that were
111          * passed in the javax Servlet init() call.
112          * 
113          * This function is primarily used when a new configuration is passed in and the
114          * PDP servlet needs to load a new PDP engine instance.
115          * 
116          * @param pipProperties - PIP configuration properties
117          * @param policyProperties  - Policy configuration properties
118          */
119         public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) {
120                 try {
121                         //
122                         // Start fresh
123                         //
124                         XACMLProperties.reloadProperties();
125                         //
126                         // Now load our init properties
127                         //
128                         XACMLProperties.getProperties().putAll(XACMLRest.restProperties);
129                         //
130                         // Load our policy properties
131                         //
132                         if (policyProperties != null) {
133                                 XACMLProperties.getProperties().putAll(policyProperties);
134                         }
135                         //
136                         // Load our pip config properties
137                         //
138                         if (pipProperties != null) {
139                                 XACMLProperties.getProperties().putAll(pipProperties);
140                         }
141                 } catch (IOException e) {
142                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties");
143                 }
144                 //
145                 // Dump them
146                 //
147                 if (logger.isDebugEnabled()) {
148                         try {
149                                 logger.debug(XACMLProperties.getProperties().toString());                               
150                         } catch (IOException e) {
151                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties");
152                         }
153                 }
154         }
155         
156         /**
157          * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
158          * 
159          * @param request - Servlet request (from a POST/GET/PUT/etc.)
160          */
161         public static void dumpRequest(HttpServletRequest request) {
162                 if (logger.isDebugEnabled()) {
163                         // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines
164                         if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))  ) {
165                                 //logger.debug("GET type=hb : heartbeat received");
166                                 PolicyLogger.debug("GET type=hb : heartbeat received");
167                                 return;                         
168                         }
169                         logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort());
170                         logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
171                         Enumeration<String> en = request.getHeaderNames();
172                         logger.debug("Headers:");
173                         while (en.hasMoreElements()) {
174                                 String element = en.nextElement();
175                                 Enumeration<String> values = request.getHeaders(element);
176                                 while (values.hasMoreElements()) {
177                                         String value = values.nextElement();
178                                         logger.debug(element + ":" + value);
179                                 }
180                         }
181                         logger.debug("Attributes:");
182                         en = request.getAttributeNames();
183                         while (en.hasMoreElements()) {
184                                 String element = en.nextElement();
185                                 logger.debug(element + ":" + request.getAttribute(element));
186                         }
187                         logger.debug("ContextPath: " + request.getContextPath());
188                         if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
189                                 // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string.
190                                 // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file).
191                                 // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters,
192                                 // and once the content is read it cannot be read again.
193                                 // Thus for PUT and POST we must avoid reading the content here so that the main code can read it.
194                                 logger.debug("Query String:" + request.getQueryString());
195                                 try {
196                                         if (request.getInputStream() == null) {
197                                                 logger.debug("Content: No content inputStream");
198                                         } else {
199                                                 logger.debug("Content available: " + request.getInputStream().available());
200                                         }
201                                 } catch (Exception e) {
202                                         logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)" +e);
203                                 }
204                         } else {
205                                 logger.debug("Parameters:");
206                                 Map<String, String[]> params = request.getParameterMap();
207                                 Set<String> keys = params.keySet();
208                                 for (String key : keys) {
209                                         String[] values = params.get(key);
210                                         logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
211                                 }
212                         }
213                         logger.debug("Request URL:" + request.getRequestURL());
214                 }
215         }
216 }