Disable SecurityFilter
[sdc.git] / catalog-fe / src / main / java / org / openecomp / sdc / fe / servlets / PortalServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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.openecomp.sdc.fe.servlets;
22
23 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
24 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
25 import org.onap.sdc.security.AuthenticationCookie;
26 import org.onap.sdc.security.RepresentationUtils;
27 import org.openecomp.sdc.common.impl.MutableHttpServletRequest;
28 import org.openecomp.sdc.common.log.wrappers.Logger;
29 import org.openecomp.sdc.fe.Constants;
30 import org.openecomp.sdc.fe.config.Configuration;
31 import org.openecomp.sdc.fe.config.ConfigurationManager;
32 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
33
34 import javax.servlet.RequestDispatcher;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.Cookie;
37 import javax.servlet.http.HttpServlet;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40 import javax.ws.rs.GET;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.core.Context;
43 import java.io.IOException;
44 import java.util.Enumeration;
45 import java.util.List;
46
47 /**
48  * Root resource (exposed at "/" path)
49  */
50 @Path("/")
51 public class PortalServlet extends HttpServlet {
52
53     private static Logger log = Logger.getLogger(PortalServlet.class.getName());
54     private static final long serialVersionUID = 1L;
55
56     public static final String MISSING_HEADERS_MSG = "Missing Headers In Request";
57     private static final String AUTHORIZATION_ERROR_MSG = "Autherization error";
58     private static final String NEW_LINE = System.getProperty("line.separator");
59
60
61     /**
62      * Entry point from ECOMP portal
63      */
64     @GET
65     @Path("/portal")
66     @Override
67     public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
68         try {
69             addRequestHeadersUsingWebseal(request, response);
70         } catch (Exception e) {
71             FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
72             log.error("Error during getting portal page", e);
73         }
74     }
75
76     /**
77      * Building new HTTP request and setting headers for the request The request
78      * will dispatch to index.html
79      *
80      * @param request
81      * @param response
82      * @throws ServletException
83      * @throws IOException
84      */
85     private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
86
87         response.setContentType("text/html");
88
89         // Create new request object to dispatch
90         MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
91
92         // Get configuration object (reads data from configuration.yaml)
93         Configuration configuration = getConfiguration(request);
94
95         // Check if we got header from webseal
96         String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
97                 String firstNameFromCookie = "";
98                 String lastNameFromCookie  = "";
99         if (null == userId) {
100             // Authentication via ecomp portal
101             try {
102                 String userIdFromCookie = getUserIdFromCookie(request);
103                 if (("").equals(userIdFromCookie)) {
104                     // This is probably a webseal request, so missing header in request should be printed.
105                     response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
106                 }
107                 userId = userIdFromCookie;
108             } catch (Exception e) {
109                 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
110                 log.error("Error during adding request header", e);
111             }
112         }
113
114         // Replace webseal header with open source header
115         mutableRequest.putHeader(Constants.USER_ID, userId);
116
117
118
119
120                 
121         // Getting identification headers from configuration.yaml
122         // (identificationHeaderFields) and setting them to new request
123         // mutableRequest
124         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
125         for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
126             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
127             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
128         }
129
130         // Getting optional headers from configuration.yaml
131         // (optionalHeaderFields) and setting them to new request mutableRequest
132         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
133         for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
134             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
135             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
136         }
137
138         // Print headers from original request for debug purposes
139         printHeaders(request);
140
141         // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
142         // Via ecomp portal do not need to check the headers.
143         boolean allHeadersExist = true;
144         if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
145             allHeadersExist = checkHeaders(mutableRequest);
146         }
147
148         if (allHeadersExist) {
149             addCookies(response, mutableRequest, getMandatoryHeaders(request));
150             addCookies(response, mutableRequest, getOptionalHeaders(request));
151                         firstNameFromCookie  = getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
152                         lastNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
153
154                         //To be fixed
155                         //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
156             RequestDispatcher rd = request.getRequestDispatcher("index.html");
157             rd.forward(mutableRequest, response);
158         } else {
159             response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
160         }
161     }
162
163         boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
164                 boolean isBuildCookieCompleted = true;
165                 AuthenticationCookie authenticationCookie = null;
166                 Cookie authCookie = null;
167                 Configuration.CookieConfig confCookie =
168                                 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
169
170                 //create authentication and send it to encryption
171
172                 String encryptedCookie = "";
173                 try {
174                         authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
175                         String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
176                         encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
177                 } catch (Exception e) {
178                         isBuildCookieCompleted=false;
179                         log.error(" Cookie Encryption failed ", e);
180                 }
181
182                 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
183                 authCookie.setPath(confCookie.getPath());
184                 authCookie.setDomain(confCookie.getDomain());
185                 authCookie.setHttpOnly(true);
186
187                 // add generated cookie to response
188                 if (isBuildCookieCompleted) {
189                         response.addCookie(authCookie);
190                         return true;
191                 }
192                 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
193                 return false;
194         }
195
196     /**
197      * Print all request headers to the log
198      *
199      * @param request
200      */
201     private void printHeaders(HttpServletRequest request) {
202
203         if (log.isDebugEnabled()) {
204             StringBuilder builder = new StringBuilder();
205             String sessionId = "";
206             if (request.getSession() != null) {
207                 String id = request.getSession().getId();
208                 if (id != null) {
209                     sessionId = id;
210                 }
211             }
212
213             builder.append("Receiving request with headers:" + NEW_LINE);
214             log.debug("{}", request.getHeaderNames());
215             @SuppressWarnings("unchecked")
216             Enumeration<String> headerNames = request.getHeaderNames();
217             if (headerNames != null) {
218                 while (headerNames.hasMoreElements()) {
219                     String headerName = headerNames.nextElement();
220                     String headerValue = request.getHeader(headerName);
221                     builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
222                 }
223             }
224
225             log.debug(builder.toString());
226         }
227
228     }
229
230     /**
231      * Add cookies (that where set in the new request headers) in the response
232      * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
233      *
234      * @param response
235      * @param request
236      * @param headers
237      */
238     private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
239         for (int i = 0; i < headers.length; i++) {
240             String currHeader = headers[i];
241             String headerValue = request.getHeader(currHeader);
242             if (headerValue != null) {
243                 final Cookie cookie = new Cookie(currHeader, headerValue);
244                 cookie.setSecure(true);
245                 response.addCookie(cookie);
246             }
247         }
248     }
249
250     /**
251      * Get mandatory headers (identificationHeaderFields) String array, and
252      * checks that each header exists in the new request
253      *
254      * @param request
255      * @return boolean
256      */
257     private boolean checkHeaders(HttpServletRequest request) {
258         String[] mandatoryHeaders = getMandatoryHeaders(request);
259
260         boolean allHeadersExist = true;
261         for (int i = 0; i < mandatoryHeaders.length; i++) {
262             String headerValue = request.getHeader(mandatoryHeaders[i]);
263             if (headerValue == null) {
264                 allHeadersExist = false;
265                 break;
266             }
267         }
268         return allHeadersExist;
269     }
270
271     /**
272      * Get mandatory headers (identificationHeaderFields) from
273      * configuration.yaml file and return String[]
274      *
275      * @param request
276      * @return String[]
277      */
278     private String[] getMandatoryHeaders(HttpServletRequest request) {
279         Configuration configuration = getConfiguration(request);
280         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
281         String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
282         for (int i = 0; i < identificationHeaderFields.size(); i++) {
283             mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
284         }
285         return mandatoryHeaders;
286     }
287
288     /**
289      * Get optional headers (optionalHeaderFields) from configuration.yaml file
290      * and return String[]
291      *
292      * @param request
293      * @return String[]
294      */
295     private String[] getOptionalHeaders(HttpServletRequest request) {
296         Configuration configuration = getConfiguration(request);
297         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
298         String[] optionalHeaders = new String[optionalHeaderFields.size()];
299         for (int i = 0; i < optionalHeaderFields.size(); i++) {
300             optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
301         }
302         return optionalHeaders;
303     }
304
305     /**
306      * Return Configuration object to read from configuration.yaml
307      *
308      * @param request
309      * @return Configuration
310      */
311     private Configuration getConfiguration(HttpServletRequest request) {
312         ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
313         return configManager.getConfiguration();
314     }
315
316     private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
317         boolean newHeaderIsSet = false;
318         for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
319             String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
320             if (headerValue != null) {
321                 newRequest.putHeader(newHeaderToSet, headerValue);
322                 newHeaderIsSet = true;
323             }
324         }
325         return newHeaderIsSet;
326     }
327
328     private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
329         String userId = "";
330         Cookie[] cookies = request.getCookies();
331         Cookie userIdcookie = null;
332         if (cookies != null) {
333             for (Cookie cookie : cookies) {
334                 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
335                     userIdcookie = cookie;
336                 }
337             }
338         }
339         if (userIdcookie != null) {
340             userId = CipherUtil.decrypt(userIdcookie.getValue());
341         }
342         return userId;
343         }
344
345         private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
346                 String value = "";
347                 Cookie[] cookies = request.getCookies();
348                 Cookie valueFromCookie = null;
349                 if (cookies != null)
350                         for (Cookie cookie : cookies) {
351                                 if (cookie.getName().endsWith(cookieName)) {
352                                         valueFromCookie = cookie;
353                                 }
354                         }
355                 if (valueFromCookie != null) {
356                         value = valueFromCookie.getValue();
357                 }
358
359                 return value;
360     }
361 }